4

Say a is a symbolic link to b. I am looking for a simple command to remove both a and b at once that does not require me to know about b.

5

Apparently I am not allowed to comment, so here as an answer: Since a is the link, we need the recursive option on the dereferenced directory...

rm -rf "$(readlink -f "a")"; rm -f "a"
  • 1
    And it is not a bad answer. Although you could detail more, what it does and how. – peterh - Reinstate Monica Sep 25 '17 at 2:39
  • 1
    Welcome to unix.se! Yours is an answer and thus accepted as such. So in a way it's a good thing you are not allowed to comment - yet 😉‎ – Tobias Kienzler Sep 25 '17 at 6:21
2

My current solution is

rm -rf "$(readlink -f "a")"; rm -f "a"

But maybe there's something easier?

  • 2
    Nothing easier, you need to remove the symlink and the directory separately. I strongly urge you to use readlink -f there, mainly because if a actually has directory components (foo/bar), $(readlink a) is relative to the location where the link is (foo). And don't forget to double quote all variable and command substitutions. Also, you don't need -r to remove a symbolic link. Thus: rm -f "$(readlink -f "a")"; rm -rf "a" – Gilles 'SO- stop being evil' May 31 '11 at 10:06
  • @Gilles: good points, edited them in, thank you – Tobias Kienzler May 31 '11 at 11:11
  • 1
    @Gilles: As Cruisen just noticed (after six years), you put the r on the wrong command. – Scott Sep 25 '17 at 5:09
  • @Scott Thanks for the note, I never noticed that... – Tobias Kienzler Sep 25 '17 at 6:19
1

Some systems will dereference the symlink when you add a trailing slash (at least if the symlink points to a directory):

mkdir -p b/c && touch b/c/foo && ln -s b/c a

rm -rf a/ && rm -f a
# removed "b/c" and "a"

The POSIX standard has changed a bit (see Pathname Resolution in IEEE Std 1003.1, 2004 Edition vs. IEEE Std 1003.1-2008), but it seems like the behavior for a pathname with a trailing slash and a final pathname components that is a symlink is (mostly) the same: the symlink is resolved.

Not all systems implement this behavior though (see comment by Gilles).

  • 1
    This doesn't work on many systems. GNU coreutils 8.5 gets confused as to the nature of a/ (rm: cannot remove `a': Not a directory), and if you explicitly specify a/. it understandably can't cope (rm: cannot remove directory: `a/.'). OpenBSD just treats a/ like a (rm -r a/ removes the symlink). – Gilles 'SO- stop being evil' Jun 1 '11 at 8:15
  • @Gilles: (changed “many” to “some”); it is unfortunate that readlink(1) is also not portable (especially its options). – Chris Johnsen Jun 1 '11 at 8:36

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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