Hello,

If "l" is a symlink to a directory, rm -r l/ recursively removes the contents 
of the target directory and only then fails, because removing the entry "l/" 
itself is rejected with ENOTDIR. With -f the failure is silent and the exit 
status is 0. I first noticed this on MSYS2 (Windows) and then reproduced it 
with GNU coreutils 9.4 on Linux:


```
$ rm --version | head -1
rm (GNU coreutils) 9.4
$ mkdir d
$ touch d/f
$ ln -s d l
$ rm l/
rm: cannot remove 'l/': Is a directory
$ ls d
f
$ rm -r l/
rm: cannot remove 'l/': Not a directory
$ ls -A d
$                   # d is now empty; both d and l still exist
$ touch d/f
$ rm -rf l/; echo $?
0
$ ls -A d
$                   # d/f is gone, with no diagnostic at all
```


I understand that a trailing slash makes "l/" resolve to the directory, and 
that this was discussed in bug#12339. I am not asking to change how "l/" 
resolves. My concern is narrower:


1. The contents are destroyed before any diagnostic is issued, and with -f 
there is never one. The end state (contents gone, directory kept, link kept, 
error reported) is neither "remove the link" nor "remove the directory". 
Removing a directory's contents through a slash-terminated symlink is almost 
never what the user intended, and it is increasingly easy to hit with scripts 
and automatically generated commands that append "/" to directory paths.
2. The diagnostics contradict each other: rm l/ says "Is a directory" while rm 
-r l/ says "Not a directory". This was already pointed out on this list in 2003 
("Bug: Symlink removal").


Proposal: when recursive removal is requested and an operand ends in a slash 
while its last component (after stripping the slashes) is a symbolic link, 
refuse that operand before descending into it, with a diagnostic such as


```
rm: refusing to remove 'l/': it is a symbolic link to a directory;
use 'rm l' to remove the link
```


and a non-zero exit status, regardless of -f. This would be similar in spirit 
to the --preserve-root safeguard. If an opt-in or opt-out option is preferred, 
that would work for me as well.


Would such a change be acceptable? If so, I can try to prepare a patch with a 
test.


Thanks,
Bayes

Reply via email to