Ubuntu – Delete directory by referencing symbolic link

command linermscriptssymbolic-link

To set up the question, imagine this scenario:

mkdir ~/temp
cd ~/
ln -s temp temporary

rm -rf temporary, rm -f temporary, and rm temporary each will remove the symbolic link but leave the directory ~/temp/.

I have a script where the name of the symbolic link is easily derived but the name of the linked directory is not.

Is there a way to remove the directory by referencing the symbolic link, short of parsing the name of the directory from ls -od ~/temporary?

Best Answer

You can use the following command:

rm -rf $(ls -l ~/temporary | awk '{print $NF}')

If you don't want to parse ls, then you can use:

rm -rf $(file ~/temporary | awk '{print $NF}' | tr -d "\`\',")

or simple:

rm -rf $(readlink ~/temporary)

To take care of spaces both in the name of the directory that in the name of the link, you can modify the last command as follows

rm -rf "$(readlink ~/"temporary with spaces")"
Related Question