Remove Symbolic Links to Directories
It is certainly easy create symbolic links or shortcuts to other files in Linux and they are used all the time. Deleting them is not difficult, however you have to take care when you need to remove symbolic links to directories. The reality is that it is still easy but you have to know and navigate the pitfalls. In the demonstration we will show how not to delete the symbolic link as well as the correct way. The incorrect way will also delete the contents of the directory which we do not want. Be sure to take on your own systems and only test on play data. In the lab we use CentOS 7.2 but this applies to any Linux system.
I have created a symbolic in the root user’s home directory that points to the /packages directory. I have left it with the same name so I have a symbolic link /root/packages that is a shortcut to /packages. The following output from the command ls will demonstrate the setup that we have.
# cd ; ls -l
The command used to create the symbolic link was:
# cd ; ln -s /packages .
We are more interested in trying to remove the link without effecting the target. This is where tab-completion, which is normally your friend, becomes your enemy. A symlink is just a file that points to another file, even if the target is a directory. The link itself is just a file. If we try to remove the link by the command:
# rm packages/
It will fail. The problem is that the more we become used to tab-completion we type a little of the name packages and the system fills out the rest including the trailing /.
This is where we may then be tempted to use rm -rf packages/ . This is bad. It will not remove the symbolic link but will remove the contents of the target directory. We demonstrate this in the video but I urge caution and to do this only with test data.
To remove the symbolic link to a directory we simply omit the trailing slash.
# rm packages
Or I prefer to use the unlink command
# unlink packages
Either way we need to ensure the trailing slash is not used. The video takes you through the process: