Safely and atomically change a symlink target

0

It can be tricky to change the target of a symlink in a production environment where that symlink is accessed often and unpredictably. The normal method is to remove the old symlink, then create the new one. If you have a symlink that is accessed often or unpredictably there is a chance that something will try to access it between these operations and have bad results.

The easiest method for changing a symlink is to use “ln -f” which will unlink the old symlink then create a new one. Again this is not atomic but will work in most traditional situations.

To safely change the target of symbolic link, you will first need to create a temporary symlink to the new target then rename it atomically using mv to the old symlink.

Since mv is an atomic operation, the symlink will always exist and there is no race condition.

Share.