views:

677

answers:

5

I am trying to check if a symbolic link exists from korn shell script using "-h filename" command.This works good on HP boxes.

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

+3  A: 

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.

whaley
+1  A: 

Looks like that should work, it's mentioned in all the man pages for test.

Douglas Leeder
+1  A: 

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
Chris Quenelle
+3  A: 

-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.

Brian Campbell
A: 

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.

Sachin Chourasiya