天天看点

linux 目录软链接 带'\'和不带'\'的区别

目录软链接时注意带'/'和不带'/'的区别

[[email protected] newdir]#ll 
total 4
drwxr-xr-x. 2 root root 4096 May 31 19:45 dir1
lrwxrwxrwx. 1 root root    4 May 31 19:44 dir2 -> dir1
[[email protected] newdir]#
[[email protected] newdir]#ll -id dir1 dir1/
136112 drwxr-xr-x. 2 root root 4096 May 31 19:45 dir1
136112 drwxr-xr-x. 2 root root 4096 May 31 19:45 dir1/
[[email protected] newdir]#
[[email protected] newdir]#ll -id dir2 dir2/
136113 lrwxrwxrwx. 1 root root    4 May 31 19:44 dir2 -> dir1    
136112 drwxr-xr-x. 2 root root 4096 May 31 19:45 dir2/    #目录带'/'时inode和目标目录一致
[[email protected] newdir]#
           

注意:

rm -rf dir2/        #带'/',此时删除的是目标目录dir1中的文件

[[email protected] newdir]#ll
total 4
drwxr-xr-x. 2 root root 4096 May 31 19:58 dir1
lrwxrwxrwx. 1 root root    4 May 31 19:58 dir2 -> dir1
[[email protected] newdir]#ls dir1
file1  file2
[[email protected] newdir]#rm -rf dir2/   #带/,此时删除的是目标目录dir1中的文件
[[email protected] newdir]#ll
total 4
drwxr-xr-x. 2 root root 4096 May 31 19:59 dir1
lrwxrwxrwx. 1 root root    4 May 31 19:58 dir2 -> dir1
[[email protected] newdir]#ls dir1
[[email protected] newdir]#
           

rm -rf dir2       #不带'/’,此时删除的是dir2本身软链接

[[email protected] newdir]#ll
total 4
drwxr-xr-x. 2 root root 4096 May 31 20:03 dir1
lrwxrwxrwx. 1 root root    4 May 31 19:58 dir2 -> dir1
[[email protected] newdir]#ls dir1
file1  file2
[[email protected] newdir]#rm -rf dir2     #不带/,此时删除的是dir2本身软链接
[[email protected] newdir]#ll
total 4
drwxr-xr-x. 2 root root 4096 May 31 20:03 dir1
[[email protected] newdir]#ls dir1
file1  file2
[[email protected] newdir]#
           

 目录创建软链接注意目录不能事先存在:

[[email protected] newdir]#ll
total 8
drwxr-xr-x. 2 root root 4096 May 31 20:05 dir1
drwxr-xr-x. 2 root root 4096 May 31 20:05 dir2
[[email protected] newdir]#ln -s dir2 dir1
[[email protected] newdir]#ll
total 8
drwxr-xr-x. 2 root root 4096 May 31 20:05 dir1
drwxr-xr-x. 2 root root 4096 May 31 20:05 dir2
[[email protected] newdir]#ll dir1
total 0
lrwxrwxrwx. 1 root root 4 May 31 20:05 dir2 -> dir2   //因为dir1目录事先存在,所以会在dir1中
                                                     自动创建一个dir2链接        
[[email protected] newdir]#
           

结合:

1、目录创建软链接时,目录不能事先存在

2、删除目录软链接时,建议不要带递归选项r,直接rm -f  dir2删除,防止 rm -rf dir2/时误删目标目录中的文件。

继续阅读