您的位置:首页 > 运维架构 > Linux

Linux中软链接与硬链接详细解读

2018-01-03 18:36 204 查看
目标:1.测试环境模拟2.软链接特性3.硬链接特性4.总结

1.测试环境模拟

12345678910111213[root@localhost home]# mkdir test 创建测试文件夹[root@localhost home]# cd test/ 进入测试文件夹[root@localhost test]# touch link 创建原文件link[root@localhost test]# echo "my name is link">>link 写入内容到原文件link[root@localhost test]# cat link 查看原文件内容my name is link[root@localhost test]# ln -s link softlink 创建软链接[root@localhost test]# ln link hardlink 创建硬链接[root@localhost test]# lltotal 8-rw-r--r--. 2 root root 16 Dec 8 18:21 hardlink 硬链接-rw-r--r--. 2 root root 16 Dec 8 18:21 link 原文件lrwxrwxrwx. 1 root root 4 Dec 8 18:22 softlink -> link 软链接

2.软链接特性

123-rw-r--r--. 2 root root 16 Dec 8 18:21 link 原文件
lrwxrwxrwx. 1 root root 4 Dec 8 18:22 softlink -> link 软链接
对比差别是不是发现有几点不同?1.原文件inode为2软链接为12.权限不同3.文件大小不同4.软链接后面有个指向link的标志

12[root@localhost test]# cat softlinkmy name is link
软链接内容一样。

1234[root@localhost test]# rm softlinkrm: remove symbolic link ‘softlink’? y[root@localhost test]# cat linkmy name is link
删除软链接原文件是正常的

1234[root@localhost test]# rm linkrm: remove regular file ‘link’? y[root@localhost test]# cat softlinkcat: softlink: No such file or directory
删除原文件软链接找不到文件了,综上证明软链接就是个快捷方式而已!!!如果我把软链接改名称会发生什么?
1234567[root@localhost test]# mv softlink testsoftlink[root@localhost test]# lltotal 8-rw-r--r--. 1 root root 16 Dec 8 18:36 linklrwxrwxrwx. 1 root root 4 Dec 8 18:34 testsoftlink -> link[root@localhost test]# cat testsoftlinkmy name is link
实验证明改名并没有什么卵用,打开软链接照样可以看到内容,为什么?因为linux识别一个文件不看名称,看inode值!!!也就是说inode值相同文件内容一样。那么文件可以创建软链接,目录可以吗?
12345[root@localhost test]# mkdir wj[root@localhost test]# ln -s wj softwj[root@localhost test]# lllrwxrwxrwx. 1 root root 2 Dec 8 18:54 softwj -> wjdrwxr-xr-x. 2 root root 6 Dec 8 18:54 wj
目录可以创建软链接

3.硬链接特性

123456[root@localhost test]# lltotal 8-rw-r--r--. 2 root root 16 Dec 8 18:36 hardlink-rw-r--r--. 2 root root 16 Dec 8 18:36 link[root@localhost test]# cat hardlinkmy name is link
观察得出硬链接就是个原文件的备份

1234[root@localhost test]# rm linkrm: remove regular file ‘link’? y[root@localhost test]# cat hardlinkmy name is link
删除原文件,硬链接是可以看到内容的,so。这就是与软链接的不同之处之一。那么硬链接是否可以像软链接一样创建目录链接呢?
123[root@localhost test]# mkdir cs[root@localhost test]# ln cs hardcsln: ‘cs’: hard link not allowed for directory
不可以的。为什么呢?因为那个唯一值!如果目录inode一样会怎么样?在访问软链接的时候通过软链接直接的跳转到原文件,这样就访问了内容在访问软链接目录的时候通过遍历目录内容也可以找到,就算文件夹里面inode值有一样的循环了,linux可以在8个循环内终结。但是如果我们的硬链接访问了,其实原文件变不变与它已经没有关系了我们的硬链接如果有硬链接目录,那么遍历的时候遇到inode值一样的目录里面的内容,全部遍历一遍,环路至少在目录的linux系统中终结不了,所以硬链接目录是不能创建滴!!!

4.总结

软链接类似快捷方式,原文件内容变了软链接的也会变,影响文件的不是名称而是inode值,软链接是可以创建软链接目录的。硬链接类似备份,原文件内容变化不影响硬链接,所以通常在工作用作为快照使用,硬链接没有硬链接目录。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息