Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

When running (on linux different ubuntu variations):

>ln -s dir_1 symlink_dir
>ln -s dir_2 symlink_dir

It fails without telling that it fails. But if you do the same thing on a file instead or, add v to the option it does tell you that it fails:

>ln -s file_1 symlinkg_file
>ln -s file_2 symlinkg_file

or

>ln -sv dir_1 symlink_dir
>ln -sv dir_2 symlink_dir

It fails with the error msg:

ln: failed to create symbolic link

For me this seems to be a very strange behaviour? Is there a reason for this?

share|improve this question

3 Answers 3

up vote 14 down vote accepted

Because in the second ln it doesn't fail it creates a

symlink_dir/dir_2 -> dir_2

symbolic link

Do a:

ls -l symlink_dir/dir_2

And you'll see a (probably broken) symlink there.

That's how ln is meant to work if the target is a directory (or a symlink to a directory).

A third ln could fail because there's already a dir_2 inside symlink_dir (aka dir_2).

share|improve this answer
    
I see. Then the second "ln -sv dir_2 symlink_dir" will then then print the error msg because it is a broken link or something. –  giZm0 Oct 16 '12 at 8:44
1  
No, a second invocation will print the error because a link at symlink_dir/dir_2 already exists. –  Jim Paris Oct 16 '12 at 18:20

As is desired, specifying -n will make ln fail in the second command:

$ ln -ns realdir symdir
$ ln -ns realdir symdir
ln: creating symbolic link `symdir' to `realdir': File exists

Note that -v is of course irrelevant to the outcome.

share|improve this answer

You can see what happens and achieve desired behavior with ln options. Use this alias for ln:

alias ln='\ln -vsn'

ln options:

   -v, --verbose
          print name of each linked file
   -f, --force
          remove existing destination files
   -n, --no-dereference
          treat destination that is a symlink to a directory as if it were a normal file
share|improve this answer
4  
I would strongly recommend against putting a --force option in any alias, there's a reason they're not the default behavior. –  Kevin Oct 16 '12 at 13:22
    
Just -sn (or -ns) is sufficient to make ln fail as desired. –  A-B-B Apr 2 at 20:13

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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