5
if [ -h "demo" ]; then
    echo "-h: true"
fi
if [ -L "demo" ]; then
    echo "-L: true"
fi

I found that both "-h" and "-L" can be used to determine whether the specified file is a link. What is the difference between them?

3
  • 1
    It's not "in bash". [ is a command that requires its last argument to be ], so it looks like some special syntax; but it's still a command like ls or cat. [ … ] is equivalent to test … where test is a command that doesn't look like some special syntax. [ and test are builtins in Bash, but they behave like commands nevertheless. You can use [ as a standalone executable (it may be /usr/bin/[). My point is -h and -L in question are not directly related to Bash. They belong to the specification of [ or test. Commented Dec 25, 2022 at 10:47
  • 3
    @KamilMaciorowski, though since it is builtin, anyone using [ in Bash would get any Bash-specific differences if there were any...
    – ilkkachu
    Commented Dec 25, 2022 at 22:51
  • 1
    @ilkkachu echo is also a builtin in Bash, but I would expect "what is -e in Bash?" to refer to bash -e, not to echo -e. And there is [ -e; and echo -n and [ -n. By your reasoning, "what is the difference between -e and -n in bash?" may refer to the echo builtin or to the [ builtin, or to any builtin. I reject this ambiguity. The title was wrong. Commented Dec 26, 2022 at 6:15

2 Answers 2

6

What is the difference between "-h" and "-L" in bash?

They both exist for legacy reasons, to be compatible between different versions of Unix.

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.

Some versions of Solaris test only support -h, and (back in 2003) some software has switched to -h for compatibility reasons.

So it's probably best to use -h

Source: Difference between test -h and test -L, answer by Brian Campbell

1

Looking at an AlmaLinux 8.7 installation:

  1. man test indicates the two options are the same:
        -h FILE
               FILE exists and is a symbolic link (same as -L)
    <snip>
        -L FILE
               FILE exists and is a symbolic link (same as -h)
    
  2. man bash just reports the same help text for both options, without mentioning they are the same:
        -h file
               True if file exists and is a symbolic link.
     <snip>
        -L file
               True if file exists and is a symbolic link.
    

From the above man text, it isn't clear which one will have best compatibility with other distributions.

As @DavidPostill has already noted, research is required to identity which option has best compatibility.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .