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?

Chuck Burgess
  • 11,600
  • 5
  • 41
  • 74

3 Answers3

65
ln -sfn /other/dir new_dir

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

ire_and_curses
  • 68,372
  • 23
  • 116
  • 141
  • 1
    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.` – redent84 Mar 09 '11 at 21:37
  • 1
    `-n` is equivalent to `-h` (at least on MacOS X) – redent84 Mar 09 '11 at 21:39
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.

redent84
  • 18,901
  • 4
  • 62
  • 85
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.

Community
  • 1
  • 1
Mischa
  • 693
  • 8
  • 15