Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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.

share|improve this question
up vote 1 down vote accepted

My current solution is

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

But maybe there's something easier?

share|improve this answer
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 May 31 '11 at 10:06
@Gilles: good points, edited them in, thank you – Tobias Kienzler May 31 '11 at 11:11

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

share|improve this answer
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 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 posting your answer, you agree to the privacy policy and terms of service.

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