1

When I have a symlink for a folder and then try it again with -sf option I end up having another symlink inside the original source folder symlinking to itself. Why is this happening and how do I make sure duplicate symlinks are not created ?

➜  foo pwd
/home/ubuntu/foo
➜  foo ln -sf ~/foo/bar ~/foo/baz
➜  foo tree
.
├── bar
│   └── test.sh
└── baz -> /home/ubuntu/foo/bar

2 directories, 1 file
➜  foo ln -sf ~/foo/bar ~/foo/baz
➜  foo tree
.
├── bar
│   ├── bar -> /home/ubuntu/foo/bar
│   └── test.sh
└── baz -> /home/ubuntu/foo/bar

3 directories, 1 file

Distro : Ubuntu 14.04.5 LTS (GNU/Linux 3.13.0-106-generic x86_64
shell : zsh with Oh my zsh plugin

4
  • Huh? Doesn't make sense to me. You create a link called baz pointing to ~/foo/bar. Then you use the same command again, why would the new generated link be called bar instead of baz? You either have a copy paste error or something is not right. – Ziazis May 18 '17 at 10:48
  • What I think you actually did was first time ln -sf ~/foo/bar ~/foo/baz second time ln -sf ~/foo/bar ~/foo/bar which created the second link. – Ziazis May 18 '17 at 10:50
  • @Ziazis Copy pasted from my terminal and it was the original output. I should have used -n option. Please refer to my answer below – Wordzilla May 18 '17 at 10:50
  • ln wouldn't create another link in the same directory. It would say there is already one. Also it wouldn't randomly follow into the link itself. The -f forces it to overwrite the already created link not write inside of the link. With the -n you actually tell it to use the link as a normal directory/file and ignore it's link status. – Ziazis May 18 '17 at 10:59
3

I did some more googling and it points to me to use -n parameter as in this blog post.

Relevant manpage entry:

-n, --no-dereference
      treat LINK_NAME as a normal file if it is a symbolic link to a directory

Relevant answers from other communities with better explanations :

https://superuser.com/a/1061057/373342
https://superuser.com/a/645847/373342

1

The actual answer you need is, don't use -f if you don't want to actually overwrite something already existing.

Without that parameter you would actually get a message that tells you:

ln: failed to create symbolic link 'your/link': File exists

The -n is, in no case I could think of needed, unless you want to create a link with the same name inside the link pointed directory.

1
  • I ran into the situation when I ran the same script twice for testing purposes and had the options as -sf. I need the -f though because I need to link to another directory with the same name in a deployment so that I can point the current folder to the latest folder for every deployment. Your answer makes sense too. Thanks. – Wordzilla May 18 '17 at 11:16

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.