Repointing A Symlink To A Different Location

10th December 2020 - 3 minutes read time

​Creating a symlink is a common way of ensuring that the directory structure of a deployment will always be the same. For example you might create a symlink so that the release directory of release123/docroot will instead be just current. This is done using the ln command in the following way, the -s flag means that we use the ln (aka link) command to create a symbolic link.

ln -s release123/docroot current

This creates a symlink that looks a little bit like this.

current -> release123/docroot

The problem comes when you need to recreate that symlink, which might happen if you create another release. You can't run the ln -s command a second time as the tool will complain that the file already exists.

One option you might take would be to delete the symlink and recreate it.

  1. rm current
  2. ln -s release123/docroot current

This works fine, but even if you run this as a script there will always be a very slight delay between the symlink not existing and then pointing at the new reference. This might cause a number of errors in terms of programs not finding their files or websites being disconnected.

To get around this it is possible to use the -f flag to 'force' the ln command to recreate the symlink without deleting it first. There is a slight niggle here in that we also need to supply the -n flag (or --no-dereference) to treat the destination that is a symlink to a directory as if it were a normal file. In other words without the -n flag the command would attempt to create a new symlink inside the already existing symlink, the -n allows us to interact with the symlink itself, rather than the item it is referencing.

Therefore, to repoint the symlink in the situation we created before we would to the following.

ln -sfn release123/docroot current

Using this technique we can repoint a symlink without having to first delete it.

Add new comment

The content of this field is kept private and will not be shown publicly.