Skip to content
  • Jeff King's avatar
    always quote shell arguments to test -z/-n · 268ef4d3
    Jeff King authored and Junio C Hamano's avatar Junio C Hamano committed
    
    
    In shell code like:
    
      test -z $foo
      test -n $foo
    
    that does not quote its arguments, it's easy to think that
    it is actually looking at the contents of $foo in each case.
    But if $foo is empty, then "test" does not see any argument
    at all! The results are quite subtle.
    
    POSIX specifies that test's behavior depends on the number
    of arguments it sees, and if $foo is empty, it sees only
    one. The behavior in this case is:
    
      1 argument: Exit true (0) if $1 is not null; otherwise,
                  exit false.
    
    So in the "-z $foo" case, if $foo is empty, then we check
    that "-z" is non-null, and it returns success. Which happens
    to match what we expected.  But for "-n $foo", if $foo is
    empty, we'll see that "-n" is non-null and still return
    success. That's the opposite of what we intended!
    
    Furthermore, if $foo contains whitespace, we'll end up with
    more than 2 arguments. The results in this case are
    generally unspecified (unless the first part of $foo happens
    to be a valid binary operator, in which case the results are
    specified but certainly not what we intended).
    
    And on top of this, even though "test -z $foo" _should_ work
    for the empty case, some older shells (reportedly ksh88)
    complain about the missing argument.
    
    So let's make sure we consistently quote our variable
    arguments to "test". After this patch, the results of:
    
      git grep 'test -[zn] [^"]'
    
    are empty.
    
    Reported-by: default avatarArmin Kunaschik <megabreit@googlemail.com>
    Helped-by: default avatarJunio C Hamano <gitster@pobox.com>
    Signed-off-by: default avatarJeff King <peff@peff.net>
    Signed-off-by: default avatarJunio C Hamano <gitster@pobox.com>
    268ef4d3