Cannot overwrite Symbolic Link RedHat Linux
Asked Answered
D

3

41

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?

Darwinism answered 9/3, 2011 at 18:22 Comment(0)
W
65
ln -sfn /other/dir new_dir

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

Wald answered 9/3, 2011 at 18:30 Comment(2)
Good point. From the man page: -h If the target_file or target_dir is a symbolic link, do not follow it. This is most useful with the -f option, to replace a symlink which may point to a directory.Resilient
-n is equivalent to -h (at least on MacOS X)Resilient
R
10

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.

Resilient answered 9/3, 2011 at 18:25 Comment(0)
A
1

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.

Aurum answered 11/11, 2015 at 12:18 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.