bash if -a vs -e option

前端 未结 3 1280
执笔经年
执笔经年 2020-12-08 02:09

Both about -a and -e options in Bash documentation is said:

-a file
    True if file exists.
-e file
    True if file exists. 
         


        
3条回答
  •  無奈伤痛
    2020-12-08 02:27

    The '-a' option to the test operator has one meaning as a unary operator and another as a binary operator. As a binary operator, it is the 'and' connective (and '-o' is the 'or' connective). As a unary operator, it apparently tests for a file's existence.

    The autoconf system advises you to avoid using '-a' because it causes confusion; now I see why. Indeed, in portable shell programming, it is best to combine the conditions with '&&' or '||'.

    I think @litb is on the right track. When you have '! -a ${resin_dir}', Bash may be interpreting it as "is the string '!' non-empty and is the string in '${resin_dir}' non-empty, to which the answer is yes. The Korn shell has a different view on this, and the Bourne shell yet another view - so stay away from '-a'.

    On Solaris 10:

    $ bash -c 'x=""; if [ ! -a "$x" ] ; then echo OK ; else echo Bad; fi'
    Bad
    $ ksh -c 'x=""; if [ ! -a "$x" ] ; then echo OK ; else echo Bad; fi'
    OK
    $ sh -c 'x=""; if [ ! -a "$x" ] ; then echo OK ; else echo Bad; fi'
    sh: test: argument expected
    $
    

提交回复
热议问题