Difference between test -h and test -L

2019-04-20 15:27发布

问题:

What is the difference between test -L filename and test -h filename in ksh shell. From the man page, both were used to identify a symbolic link, but I want to know the exact difference.

Here is the description from the man page.

 -h file                 True if file exists and  is  a  sym-
                         bolic link.
 -L file                 True if file exists and  is  a  sym-
                         bolic link.

回答1:

The source code for ksh93, in file bltins/test.c, shows that these two options are treated exactly the same, except for the author's hopes for the future:

        case 'L':
        case 'h': /* undocumented, and hopefully will disappear */
            if(*arg==0 || arg[strlen(arg)-1]=='/' || lstat(arg,&statb)<0)
                    return(0);
            return(S_ISLNK(statb.st_mode));

From this I conclude that they behave exactly the same, but that -h is a legacy option and may one day disappear :-)



回答2:

It appears that they both exist for legacy reasons, to be compatible between different versions of Unix. You should be able to use either one, as they do the exact same thing, but be aware that if the system you are running on is not compliant with the latest standards, it may be missing one or the other.

Both forms are present in the Single Unix Specification version 3/POSIX 2004, with no caveats:

-h  pathname
True if pathname resolves to a file that exists and is a symbolic link. False if pathname cannot be resolved, or if pathname resolves to a file that exists but is not a symbolic link. If the final component of pathname is a symlink, that symlink is not followed.
-L  pathname
True if pathname resolves to a file that exists and is a symbolic link. False if pathname cannot be resolved, or if pathname resolves to a file that exists but is not a symbolic link. If the final component of pathname is a symlink, that symlink is not followed.

According to the test(1) man page on Mac OS X and FreeBSD (note that this warning may be outdated; it first appeared in NetBSD in 1996):

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

And apparently, some versions of Solaris test only support -h, and (back in 2003) some software has switched to -h for compatibility reasons, so -h may actually be your best bet.



回答3:

There is no difference, they are exactly the same. They probably exist to unify different test implementations pre-POSIX.



回答4:

Fedora's man page says

   -h FILE
          FILE exists and is a symbolic link (same as -L)