加入收藏 | 设为首页 | 会员中心 | 我要投稿 我爱资讯网 (https://www.52junxun.com/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 服务器 > 搭建环境 > Linux > 正文

Linux硬链接和软链接(符号链接)

发布时间:2022-11-12 11:01:01 所属栏目:Linux 来源:
导读:  【硬链接(Hard Link)】

  硬链接指通过索引节点来进行连接,在Linux为文件系统中,保存在磁盘分区中的文件不管是什么类型都给它分配一个编号,称为索引节点号;

  硬链接指的就是在Linux中,多个文
  【硬链接(Hard Link)】
 
  硬链接指通过索引节点来进行连接,在Linux为文件系统中,保存在磁盘分区中的文件不管是什么类型都给它分配一个编号,称为索引节点号;
 
  硬链接指的就是在Linux中,多个文件名指向同一索引节点;
 
  常见用途:通过建立硬链接到重要文件,防止误删,删除其实对应的是删除其中的一个硬链接,当文件对应的硬链接都被删除了,该文件才真正被删除;
 
  注意: 默认情况下,ln命令产生硬链接;
 
  [root@centos7 home]# vi 1.txt
  hello, this is 1.txt!
  [root@centos7 home]# cp -l 1.txt 2.txt # 为1.txt建立硬链接2.txt,等同于ln 1.txt 2.txt
  [root@centos7 home]# more 2.txt # 查看2.txt文件中的内容和1.txt文件内容一样
  hello, this is 1.txt!
  # 这两个文件的索引节点号,可以看见索引号一样:
  [root@centos7 home]# ls -li
  总用量 69868
  33845219 -rw-r--r--.  2 root root       44 1月  21 10:12 1.txt
  33845219 -rw-r--r--.  2 root root       44 1月  21 10:12 2.txt
  [root@centos7 home]# vi 2.txt # 编辑2.txt,在末未添加:
  hello, this is 2.txt!
  [root@centos7 home]# more 1.txt  # 查看1.txt中是否内容改动
  hello, this is 1.txt!
  hello, this is 2.txt!
  [root@centos7 home]# rm -f 1.txt # 删除1.txt
  [root@centos7 home]# more 2.txt # 查看2.txt的内容
  hello, this is 1.txt!
  hello, this is 2.txt!
  创建硬链接命令:cp -l 1.txt 2.txt等同于ln 1.txt 2.txt # 为1.txt建立硬链接2.txt
 
  【软链接】
 
  也成为符号链接(Symbolic Link),类似于Windows的快捷方式linux软链接,其中包含的是另一个文件的位置信息;
 
  [root@centos7 home]# cp -s 2.txt sLink # 为2.txt文件建立符号链接sLink,等同于ln –s 2.txt sLink
  [root@centos7 home]# ls –li # 可以看到两个文件有不同的索引节点号
  总用量 69864
  33845219 -rw-r--r--.  1 root root       44 1月  21 10:12 2.txt
  36830246 lrwxrwxrwx.  1 root root        5 1月  21 10:21 sLink -> 2.txt
  [root@centos7 home]# more sLink
  hello, this is 1.txt!
  hello, this is 2.txt!
  [root@centos7 home]# rm -f sLink # 删除符号链接,不影响源文件
  [root@centos7 home]# more 2.txt
  hello, this is 1.txt!
  hello, this is 2.txt!
  [root@centos7 home]# rm -f 2.txt # 删除2.txt
  [root@centos7 home]# ls -li
  总用量 69860
  36830246 lrwxrwxrwx.  1 root root        5 1月  21 10:21 sLink -> 2.txt
  [root@centos7 home]# more sLink
  sLink: 没有那个文件或目录
  创建符号链接命令:cp -s 2.txt sLink 等同于ln –s 2.txt sLink # 为2.txt文件建立符号链接sLink
 
  注意:
 
  只能在同种存储媒体上的文件之间创建硬链接(Hard Link),不能在不同挂载点下的文件间创建硬链接,对于后一种情况,可以使用软链接;(区分不同挂载点与同一挂载点不同目录)
 
  如跨不同的挂载点建立硬链接的报错信息:
 
  [root@centos7 home]# ln 2.txt /dev/hLink
  ln: 无法创建硬链接"/dev/hLink" => "2.txt": 无效的跨设备连接
  小结:
 
  1: 硬链接是同一文件的不同访问路径,其对应的索引节点号是一样的,删除文件其实就是删除其中的一个硬链接,如果该文件对应的硬链接都被删除了该文件才被删除,常用于保护文件;
 
  2: 符号链接类似于Windows中对应的快捷方式,删除符号链接不影响源文件,删除源文件,则对应的符号链接也没有意义
 

(编辑:我爱资讯网)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!