user358829
user358829

Reputation: 761

Deleting a folder that contains symlinks

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

Upvotes: 27

Views: 11480

Answers (4)

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.

Upvotes: 0

Noufal Ibrahim
Noufal Ibrahim

Reputation: 72745

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.

Upvotes: 23

Bohdan
Bohdan

Reputation: 17193

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

Upvotes: 2

Jordan Lewis
Jordan Lewis

Reputation: 17928

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

Upvotes: 16

Related Questions