Linux 中链接的分类
硬链接 ( Hard Link ):可以理解为只是在某个目录下新增一个文档名链接到某 inode 的关连记录。
符号链接 ( Symbolic Link ):可以理解为 Windows 中的快捷方式。
语法
[root@DB winds]# ln [-sf] source_file target_file
# 参数说明
# -s :不加任何参数就是 hard link,至于 -s 就是 symbolic link
# -f :如果目标文件存在时,就主动将目标文件直接移除后再建立
特性
下面通过一个案例说明:
# 创建一个 test 文件
[root@DB tmp]# cat test
this is a test file.
# 查看 test 的 inode
[root@DB tmp]# ls -il test
348012 -rw-r--r--. 1 root root 21 Nov 6 15:54 test
# 系统当前使用空间和 inode 的使用情况
[root@DB tmp]# du -sb;df -i /
1640898 .
Filesystem Inodes IUsed IFree IUse% Mounted on
/dev/sda2 655360 163080 492280 25% /
# 创建 test 的硬链接
[root@DB tmp]# ln test test-hl
[root@DB tmp]# ls -il test*
348012 -rw-r--r--. 2 root root 21 Nov 6 15:54 test
348012 -rw-r--r--. 2 root root 21 Nov 6 15:54 test-hl
# 系统当前使用空间和 inode 的使用情况
[root@DB tmp]# du -sb;df -i /
1640898 .
Filesystem Inodes IUsed IFree IUse% Mounted on
/dev/sda2 655360 163080 492280 25% /
# 创建一个符号链接
[root@DB tmp]# ln -s test test-sl
[root@DB tmp]# ls -il test*
348012 -rw-r--r--. 2 root root 21 Nov 6 15:54 test
348012 -rw-r--r--. 2 root root 21 Nov 6 15:54 test-hl
347973 lrwxrwxrwx. 1 root root 4 Nov 6 16:04 test-sl -> test
# 系统当前使用空间和 inode 的使用情况
[root@DB tmp]# du -sb;df -i /
1640902 .
Filesystem Inodes IUsed IFree IUse% Mounted on
/dev/sda2 655360 163081 492279 25% /
# 删除 test 文件,并查看链接文件的内容
[root@DB tmp]# rm test
rm: remove regular file ‘test’? y
[root@DB tmp]# head test-hl test-sl
==> test-hl <==
this is a test file.
head: cannot open ‘test-sl’ for reading: No such file or directory
# 重新创建 test 文件
[root@DB tmp]# touch test
[root@DB tmp]# head test test-hl test-sl
==> test <==
==> test-hl <==
this is a test file.
==> test-sl <==
总结:
- 创建硬链接,文件系统的使用空间不会增加,也不影响 inode 的使用数量;
- 创建符号链接,文件系统的使用空间会增加,inode 的使用数量也会增加;
- 创建硬链接,link 数会增加;创建符号链接,link 数不会增加;
- 删除原始文件,硬链接文件仍可用,但是符号链接文件会失效;
- 重新创建同名的文件,原有的硬链接文件不受影响,符号链接的文件会指向新创建的同名文件。
另外硬链接的使用会有两个限制:不能跨 Filesystem;不能 ln 目录;
[root@DB winds]# mkdir myMusic
[root@DB tmp]# ln myMusic myMusic-hl
ln: ‘myMusic’: hard link not allowed for directory
[root@DB tmp]# ln -s myMusic myMusic-sl
[root@DB tmp]# ls -l myMusic*
lrwxrwxrwx. 1 root root 7 Nov 6 16:35 myMusic-sl -> myMusic
myMusic:
total 0