开发者

Deleting a folder that contains symlinks

开发者 https://www.devze.com 2023-01-02 13:58 出处:网络
If I rm -rf a folder that has soft links in it, will it try to follow those links and 开发者_开发技巧delete the corresponding folder, or will it simply unlink them?

If I rm -rf a folder that has soft links in it, will it try to follow those links and 开发者_开发技巧delete the corresponding folder, or will it simply unlink them?

I have a copy of my home directory with symbolic links in it, and I'm scared to rm -rf it in case it follows those links and blows up the corresponding folders...


Generally speaking, rm doesn't "delete". It "unlinks". This means that references to a file are removed by rm. When the number of references reaches zero, the file will no longer be accessible and in time, the area of disk where it resides will be used for something else.

When you rm a directory, the stuff inside the directory is unlinked. Symbolic links are (sort of like) files with the name of their targets inside them and so they're just removed. To actually figure out what they're pointing to and then unlink the target is special work and so will not be done by a generic tool.


No. rm -rf won't follow symbolic links - it will simply remove them.

% mkdir a                                                             
% touch a/foo
% mkdir b                                                               
% ln -s a b/a                                                           
% rm -rf b                                                              
%   ls a                                                                  
foo


Here is axample:

find a b

a
a/1
a/2
b

ll

drwxr-xr-x 2 ****** ****** 4.0K Feb  6 15:11 a
lrwxrwxrwx 1 ****** ****** 1 Feb  6 15:13 b -> a

.

rm -rf b

gives

find a b

a
a/1
a/2

.

rm -rf b/

gives error:

rm: cannot remove `b/': Not a directory

Conclusion:

rm does not follow symlinks


POSIX quote

Since rm -r is POSIX we can also look at what they have to say: https://pubs.opengroup.org/onlinepubs/009604599/utilities/rm.html

The rm utility shall not traverse directories by following symbolic links into other parts of the hierarchy, but shall remove the links themselves.

The rationale section mentions a bit more:

The rm utility removes symbolic links themselves, not the files they refer to, as a consequence of the dependence on the unlink() functionality, per the DESCRIPTION. When removing hierarchies with -r or -R, the prohibition on following symbolic links has to be made explicit.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号