Chuck Burgess
Chuck Burgess

Reputation: 11574

Cannot overwrite Symbolic Link RedHat Linux

I have created a symbolic link:

sudo ln -s /some/dir new_dir

Now I want to overwrite the symbolic link to point to a new location and it will not overwrite. I have tried:

sudo ln -f -s /other/dir new_dir

I can always sudo rm new_dir, but I would rather have it overwrite accordingly if possible. Any ideas?

Upvotes: 42

Views: 15317

Answers (3)

Mischa
Mischa

Reputation: 733

Since the Link from mikeytown2s comment is broken, i will explain why redent84s answer is better:

While

ln -sfn newDir currentDir

does the job, it is not an atomic operation, as you can see with strace:

$ strace ln -snf newDir currentDir 2>&1 | grep link
unlink("currentDir")         = 0
symlink("newDir", "currentDir") = 0

This is important when you have a webserver root pointing to that symlink. It could cause errors while the symlink is deleted and created again - even in the timespan of a microsecond.

To prevent errors use instead:

$ ln -s newDir tmpCurrentDir && mv -Tf tmpCurrentDir currentDir

This will create a temporary Link and after that overwrite currentDir in an atomic operation.

Upvotes: 1

ire_and_curses
ire_and_curses

Reputation: 70172

ln -sfn /other/dir new_dir

works for me. The -n doesn't dereference the destination symlink.

Upvotes: 65

redent84
redent84

Reputation: 19239

You can create it and then move it:

sudo ln -f -s /other/dir __new_dir
sudo mv -Tf __new_dir new_dir

edit: Missing -Tf, to treat the directory as a regular file and don't prompt for overwrite.

This way you will overwrite it.

Upvotes: 10

Related Questions