日期:2014-05-16  浏览次数:20866 次

linux ln命令学习

ln命令用来给档案创建链接。

1. 使用ln命令给档案创建symbolic link。
linux系统下的symbolic link类似于windows系统的快捷方式一样。
使用ls命令查看,可以看到新创建的symbolic link有独立的inode,
也就是symbolic link会占用一个inode,但是其实际内容仍然是指向
源文件所指向的block区域。
# touch /tmp/file
# ls -lhi /tmp/file
   3441 -rw-r--r--    1 root     root            0 Jan  1 00:09 /tmp/file
#
# ln -fs /tmp/file /tmp/symbolic_link
# ls -lhi /tmp/symbolic_link
   3647 lrwxrwxrwx    1 root     root            9 Jan  1 00:10 /tmp/symbolic_link -> /tmp/file
#

2. 删除symbolic link文件,实际上就是删除这个inode,而不会影响到源文件所指向的block区域;
而如果删除了源文件,那这个symbolic link文件就基本上没用了。
# echo "link test" > /tmp/file
# cat /tmp/file
link test
#
# rm /tmp/symbolic_link
# cat /tmp/file
link test
#
# ln -fs /tmp/file /tmp/symbolic_link
#
# rm /tmp/file
# cat /tmp/symbolic_link
cat: can't open '/tmp/symbolic_link': No such file or directory
#
# ls -lhi /tmp/symbolic_link
   7357 lrwxrwxrwx    1 root     root            9 Jan  1 00:22 /tmp/symbolic_link -> /tmp/file
#

3. 使用ln命令创建hard link。
可以看到,创建hard link是使用同一个inode,而copy了一份源文件的block区域出来。
如果修改档案的内容,源文件和hard link文件对应的block区域内容都会被修改,从而保持一致性。
# touch /tmp/file
# echo "hard link test" > /tmp/file
# cat /tmp/file
hard link test
# ln /tmp/file /tmp/hard_link
# ls -lhi /tmp/file
   7996 -rw-r--r--    2 root     root           15 Jan  1 00:25 /tmp/file
# ls -lhi /tmp/hard_link
   7996 -rw-r--r--    2 root     root           15 Jan  1 00:25 /tmp/hard_link
# cat /tmp/hard_link
hard link test
#
# echo "hard link test 2" > /tmp/file
# cat /tmp/file
hard link test 2
# cat /tmp/hard_link
hard link test 2
#
# echo "hard link test 3" > /tmp/hard_link
# cat /tmp/file
hard link test 3
# cat /tmp/hard_link
hard link test 3
#

4. 删除hard link或者删除源文件,实际上只是删除其中其中一份block区域。
可以看到,虽然源文件被删除(实际上只是删除了源文件对应的block区),但是
inode仍然还在,所以仍然可以透过hard link档案来访问源文件的内容。
到了这里,就可以理解为什么inode信息中不包含文件名了;
因为如果文件名信息包含在inode中,并且创建了hard link,此时为何还需要两块不同的block区域
来储存文件信息呢?进而hard link还有什么意义呢?
# rm /tmp/file
# cat /tmp/file
cat: can't open '/tmp/file': No such file or directory
#
# cat /tmp/hard_link
hard link test 3
#
# ls -hli /tmp/hard_link
   7996 -rw-r--r--    1 root     root           17 Jan  1 00:29 /tmp/hard_link
#

5. 为目录创建symbolic link?
因为新建的symbolic link目录与源目录是同一个inode,所以对这两个目录的访问具有完全相同的表现。
# mkdir /tmp/directory
# ln -fs /tmp/directory/ /tmp/dir_sym_link
#
# ls -hdi /tmp/directory/
  14018 /tmp/directory/
# ls -hdi /tmp/dir_sym_link/
  14018 /tmp/dir_sym_link/
#
# touch /tmp/directory/file
# ls -hil /tmp/directory/file
  14781 -rw-r--r--    1 root     root            0 Jan  1 00:47 /tmp/directory/file
# ls -hil /tmp/dir_sym_link/file
  14781 -rw-r--r--    1 root  &