ln -sf source_file target_file succeeds even when source_file does not exist.

ln -f source_file target_file on the other hand fail, as expected.

How can it be tuned to give error on the first case without first testing for the file existence explicitly (i.e. not [[ -e source_file ]] && ln -sf source_file target_file)

  • 2
    I could not duplicate this behavior. For me using -s alone with a non-existent source creates a broken symlink silently. ln -f without -s must of course fail because you're asking it to increase the ref count on a non-existent inode. – Joseph R. Jul 12 '13 at 21:51
  • Can you show exacly what "two different commands" you ran and what error they produced? I suspect that you are mixing hard- and symlinks – sendmoreinfo Jul 13 '13 at 13:00
  • @sendmoreinfo You are right, I was expecting broken symlinks creation to fail just as hard links would but it doesn't. – akurtser Jul 14 '13 at 15:59

From the ln man page:

When creating hard links, each TARGET must exist.

No mention of symlinks there; in fact, this statement seems to imply that this is not the case for symlinks.

As I said in my comment on your question, when creating a symlink to a non-existent source, a broken link is created:

$ ln -sfv blah blabla
'blabla' -> 'blah'
$ file blabla
blabla: broken symbolic link to 'blah'

As far as ln is concerned, there's no reason to cry error: you asked for a symlink and it obliged. Shy of aliasing ln, I don't see a way to do what you want without explicitly checking for the existence of the source file.

  • That's the exact opposite of what I want to achieve - silent failing is the observed behavior, the expected behavior would be the explicit error given when using either -f or -s alone. When combined - it fails silently and I'd like to change that. – akurtser Jul 12 '13 at 21:46
  • @akurster I see. Would you mind adding -sf to the very first ln source_file target_file in your question, then? – Joseph R. Jul 12 '13 at 21:49
  • @akurtser Answer changed. – Joseph R. Jul 12 '13 at 21:56
  • My bad, sorry, question changed. – akurtser Jul 13 '13 at 10:15

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.