[PSA] Working with symbolic links? Don't make this dumb mistake!

Difficulty: ☆☆☆☆☆

There is one character which differentiates between deleting symbolic links, and deleting everything: /

When deleting symbolic links via rm, DO NOT EVER end directories with a forward slash. Instead of deleting the link, it deletes the files inside the linked directory!

I cannot stress this enough. I lost nothing important when I made this mistake, but it’s a lesson worth knowing before your script destroys years of work if you’re deleting symbolic links in active use!

How would you know if you screwed up? If the time it took before control of the terminal is returned wasn’t enough of a clue, you can use -v with rm for verbose output of what it’s doing.

A safer alternative

Rather than use rm for everything and be a lazy coder, the responsible thing to do is to use unlink instead. As symlinked directories are not directories the rmdir command does not work!

:brain: Previously I said rmdir does work. in my rush to bang this out I lost my brain along the way. Thank you, @Fabby for pointing this out and finding a way to mash it back into my skull.

1 Like

Actually, you should use

unlink

to remove symbolic links… This will not protect you from accidental file deletion, but it will protect you from directory deletion:

fab-root@fab-manjaro:~
$ cd /tmp
fab-root@fab-manjaro:/tmp
$ md dirfoo
fab-root@fab-manjaro:/tmp
$ ln --symbolic dirfoo lnfoobar
fab-root@fab-manjaro:/tmp
$ unlink lnfoobar/
unlink: cannot unlink 'lnfoobar/': No such file or directory

:man_shrugging:

3 Likes

Fixed, thanks.

1 Like