0

I am trying to write a function ln() (if it is not a good idea to call it ln, it may just be as well called myln() or whatever, but that is not important) in bash, such that,

  • If the short option -s does not exist, it simply performs what command ln does
  • If the short option -s does exist, it performs what command ln does unless the symbolic link(s) to be created contain broken ones. In that case, it prints a warning to stderr and does not create the link (or create it and remove it afterwards immediately)

Since the command ln takes its option in various forms that are extremely versatile, I am not sure how to write such a function to cover all the possibilities. I do know how to write it for simple usage like ln -s [absolute path 1] [absolute path 2].

It is best if the function is able to cover the usages of ln in the newest version of GNU coreutils (at the time the question is asked the newest version is 8.31), but a function that just covers the usage in POSIX is fine too.

Side note: I have written a "failproof" rm in https://codereview.stackexchange.com/a/215226/155325, I want to do something similar to make a "failproof" ln. I am using it myself and I know the consequences. I am not distributing it to someone not familiar with Linux and say "Hey you should use this rm from now on and you can forget the caveats of rm /*"

1

Not sure if this is what you're after but in your function you can use namei command to examine target file before creating a symbolic link.

$ touch file1
$ ln -s file1 file2
$ ln -s file2 file3
$ namei file3 
f: file3
 l file3 -> file2
   l file2 -> file1
     - file1
$ echo $?
0
$ rm file1 # break first symlink
$ ls -l
$ namei file3
f: file3
 l file3 -> file2
   l file2 -> file1
       file1 - No such file or directory
$ echo $?
1
  • Thank you. I guess that is a starting point. – Weijun Zhou Apr 27 at 7:28

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.