3

I am trying to check if a symbolic link exists from a KornShell (ksh) script using -h filename command. This works good on HP boxes.

Not sure what is the correct option for Linux, AIX and Solaris boxes.

Any insight regarding this?

4 Answers 4

6

-h is part of the POSIX spec; it should work everywhere that is vaguely reasonable.

According to man test on Mac OS X:

     -h file       True if file exists and is a symbolic link.  This operator
                   is retained for compatibility with previous versions of
                   this program. Do not rely on its existence; use -L instead.

-L is also standardized, so if you find anywhere that -h does not work, you should try -L instead.

1
  • Since -L exists in the POSIX spec as well, shouldn't we just recommend using -L according to the notes in your manpage?
    – palswim
    Commented Mar 14, 2019 at 20:50
5

It is -h on linux systems also, at least (bash is my shell):

lrwxrwxrwx 1 mule mule 37 Feb 27 09:43 mule.log -> /home/mule/runtime/mule/logs/mule.log
[mule@emdlcis01 ~]$ if [[ -h mule.log ]]; then echo "mule.log is a symlink that exists" ; fi
mule.log is a symlink that exists

Check man test to see the available operators you have available to use on files and strings in your given enviorment.

0
1

The best answer is to try whatever the 'test' man page says on your system. If that seems to work, look no further. However, if it doesn't seem to work, or if you have questions about more obscure options to test, then you should also check the man page for your shell to see if 'expr' or '[' are built-ins. In that case, the shell might be using an internal implementation instead of calling the expr utility from /bin. On Solaris I verified that ksh93 treats [ as a builtin (even though the man page doesn't seem to say so). From the truss output you can see that ksh is not running the expr command for [.

% truss -f -texec /bin/ksh '[ -h /home ]'
26056:  execve("/usr/bin/ksh", 0x08047708, 0x08047714)  argc = 2
26056:  execve("/usr/bin/ksh93", 0x08047708, 0x08047714)  argc = 2
26056:  execve("/usr/bin/amd64/ksh93", 0x08047704, 0x08047710)  argc = 2

% truss -f -texec /bin/ksh '/bin/expr -h /home ]'
26058:  execve("/usr/bin/ksh", 0x08047700, 0x0804770C)  argc = 2
26058:  execve("/usr/bin/ksh93", 0x08047700, 0x0804770C)  argc = 2
26058:  execve("/usr/bin/amd64/ksh93", 0x080476FC, 0x08047708)  argc = 2
26058:  execve("/bin/expr", 0x00418360, 0x00418398)  argc = 4
0

Thw two possible options are

    if [ -h filename ] 
OR
    ls -ltr | grep filename | grep ^l

If $? is 0 then file is linked otherwise its not linked, I will prefer the first option instead.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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