Linux 系统存在两种链接:硬链接 (hard link) 与软链接(又称符号链接,即 soft link 或 symbolic link)。
作用:链接为 Linux 系统解决了文件的共享使用,还带来了隐藏文件路径、增加权限安全及节省存储等好处。
若一个 inode 号对应多个文件名,则称这些文件为硬链接。换言之,硬链接就是同一个文件使用了多个别名但是他们有共同的 inode号。
对源文件(sourcefile)创建硬链接方法:
ln sourcefile targetfile
硬链接的几点特性:
文件有相同的 inode 及 data block;
只能对已存在的文件进行创建;
不能交叉文件系统创建硬链接;
不能对目录进行创建,只可对文件创建;
删除一个硬链接文件并不影响其他有相同 inode 号的文件。
# ls -li
total 0
// 只能对已存在的文件创建硬连接
# link source.file hard.link
link: cannot create link `hard.link' to `old.file': No such file or directory
//创建了文件source.file
# echo "This is an original file" > source.file
# cat source.file
This is an original file
//查看source.file 的iNode信息
# stat source.file
File: `source.file'
Size: 25 Blocks: 8 IO Block: 4096 regular file
Device: 807h/2055d Inode: 660650 Links: 2
Access: (0644/-rw-r--r--) Uid: ( 0/ root) Gid: ( 0/ root)
...
// 文件有相同的 inode 号以及 data block
# link source.file hard.link | ls -li
total 8
660650 -rw-r--r-- 2 root root 25 Sep 1 17:44 hard.link
660650 -rw-r--r-- 2 root root 25 Sep 1 17:44 source.file
// 不能交叉文件系统
# ln /dev/input/event5 /root/bfile.txt
ln: failed to create hard link `/root/bfile.txt' => `/dev/input/event5':
Invalid cross-device link
(dev目录用的是devtmps文件系统,root目录是ext4文件系统,所以不能交叉)
// 不能对目录进行创建硬连接
# mkdir -p source.dir/test
# ln source.dir/ hardlink.dir
ln: `source.dir/': hard link not allowed for directory
# ls -iF
660650 hard.link 657948 source.dir/ 660650 source.file
软链接与硬链接不同,若文件用户数据块中存放的内容是另一文件的路径名的指向,则该文件就是软连接。软链接就是一个普通文件,只是数据块内容有点特殊。软链接有着自己的 inode 号以及用户数据块。因此软链接的创建与使用没有类似硬链接的诸多限制。
对源文件(sourcefile)创建硬链接方法:
ln -s sourcefile targetfile
软连接特性:
有自己的文件属性及权限等;
可对不存在的文件或目录创建软链接;
软链接可交叉文件系统;
软链接可对文件或目录创建;
创建软链接时,链接计数 i_nlink 不会增加;
删除软链接并不影响被指向的文件,但若被指向的原文件被删除,则相关软连接被称为死链接(即 dangling link,若被指向路径文件被重新创建,死链接可恢复为正常的软链接)。
# ls -li
total 0
// 可对不存在的文件创建软链接
# ln -s source.file soft.link
# ls -liF
total 0
789467 lrwxrwxrwx 1 root root 8 Sep 1 18:00 soft.link -> old.file
// 由于被指向的文件不存在,此时的软链接 soft.link 就是死链接
# cat soft.link
cat: soft.link: No such file or directory
// 创建被指向的文件 source.file,soft.link 恢复成正常的软链接
# echo "This is an original file_A" >> source.file
# cat soft.link
This is an original file_A
// 对不存在的目录创建软链接
# ln -s source.dir soft.link.dir
# mkdir -p source.dir/test
# tree . -F --inodes
.
├── [ 789497] old.dir/
│ └── [ 789498] test/
├── [ 789495] old.file
├── [ 789495] soft.link -> old.file
└── [ 789497] soft.link.dir -> old.dir/
当然软链接的用户数据也可以是另一个软链接的路径,其解析过程是递归的。但需注意:软链接创建时原文件的路径指向使用绝对路径较好。使用相对路径创建的软链接被移动后该软链接文件将成为一个死链接(如下所示的软链接 a 使用了相对路径,因此不宜被移动),因为链接数据块中记录的亦是相对路径指向。
$ ls -li
total 2136
656627 lrwxrwxrwx 1 harris harris 8 Sep 1 14:37 a -> data.txt
656662 lrwxrwxrwx 1 harris harris 1 Sep 1 14:37 b -> a
656228 -rw------- 1 harris harris 2186738 Sep 1 14:37 data.txt 6