27

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...

4 Answers 4

23

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.

16

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
2

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

1
  • 1
    Sorry to necro an old post, but this is wrong. Indeed, rm -r will delete only the symlink itself, however, rm -r b/ will delete all contents of a (and then produces the error you reported)! It hence leaves a and b, but will have deleted a/1 and a/2. Commented Mar 12, 2021 at 11:09
0

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.