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

来源:互联网 发布:复方雄蛾强肾胶囊淘宝 编辑:程序博客网 时间:2024/06/08 06:48

【硬链接(Hard Link)】

硬链接指通过索引节点来进行连接,在Linux为文件系统中,保存在磁盘分区中的文件不管是什么类型都给它分配一个编号,称为索引节点号;
硬链接指的就是在Linux中,多个文件名指向同一索引节点;
常见用途:通过建立硬链接到重要文件,防止误删,删除其实对应的是删除其中的一个硬链接,当文件对应的硬链接都被删除了,该文件才真正被删除;
注意: 默认情况下,ln命令产生硬链接;

[root@centos7 home]# vi 1.txthello, 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总用量 6986833845219 -rw-r--r--.  2 root root       44 121 10:12 1.txt33845219 -rw-r--r--.  2 root root       44 121 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的快捷方式,其中包含的是另一个文件的位置信息;

[root@centos7 home]# cp -s 2.txt sLink # 为2.txt文件建立符号链接sLink,等同于ln –s 2.txt sLink[root@centos7 home]# ls –li # 可以看到两个文件有不同的索引节点号总用量 6986433845219 -rw-r--r--.  1 root root       44 121 10:12 2.txt36830246 lrwxrwxrwx.  1 root root        5 121 10:21 sLink -> 2.txt[root@centos7 home]# more sLinkhello, this is 1.txt!hello, this is 2.txt![root@centos7 home]# rm -f sLink # 删除符号链接,不影响源文件[root@centos7 home]# more 2.txthello, this is 1.txt!hello, this is 2.txt![root@centos7 home]# rm -f 2.txt # 删除2.txt[root@centos7 home]# ls -li总用量 6986036830246 lrwxrwxrwx.  1 root root        5 121 10:21 sLink -> 2.txt[root@centos7 home]# more sLinksLink: 没有那个文件或目录

创建符号链接命令:cp -s 2.txt sLink 等同于ln –s 2.txt sLink # 为2.txt文件建立符号链接sLink

注意:
只能在同种存储媒体上的文件之间创建硬链接(Hard Link),不能在不同挂载点下的文件间创建硬链接,对于后一种情况,可以使用软链接;(区分不同挂载点与同一挂载点不同目录)
如跨不同的挂载点建立硬链接的报错信息:

[root@centos7 home]# ln 2.txt /dev/hLinkln: 无法创建硬链接"/dev/hLink" => "2.txt": 无效的跨设备连接

小结:

1: 硬链接是同一文件的不同访问路径,其对应的索引节点号是一样的,删除文件其实就是删除其中的一个硬链接,如果该文件对应的硬链接都被删除了该文件才被删除,常用于保护文件;
2: 符号链接类似于Windows中对应的快捷方式,删除符号链接不影响源文件,删除源文件,则对应的符号链接也没有意义;

参考资料:

http://www.cnblogs.com/itech/archive/2009/04/10/1433052.html
《Linux命令行与shell脚本编程大全》 (第2版)

0 0
原创粉丝点击