How to remove the directory a symbolic link links to plus the symbolic link?

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.

Here is Solutions:

We have many solutions to this problem, But we recommend you to use the first solution because it is tested & true solution that will 100% work for you.

Solution 1

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"

Solution 2

My current solution is

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

But maybe there’s something easier?

Solution 3

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

Note: Use and implement solution 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply