Bash nonzero test case (-n), [ and [[ are doing different things

后端 未结 2 1697
既然无缘
既然无缘 2021-01-16 18:48

Usually i only use [[ for all kinds of test cases, because it\'s the most advanced way and it\'s more safe to use (Regex, ...). I know that [[ executes different code than [

相关标签:
2条回答
  • 2021-01-16 19:06

    I think that your problem is related to quotes.

    When you use [ -n $VAR ] the command that is executed won't contain any argument where $VAR should be:

    $ set -x
    $ [ -n $VAR ]
    + '[' -n ']'
    

    This means that you are essentially testing whether the string -n is non-empty, because the following two tests are equivalent:

    [ string ]    # is a shorthand for
    [ -n string ] # which is always true!
    

    If you use quotes, then you get different behaviour:

    $ [ -n "$VAR" ]
    + '[' -n '' ']'
    

    Now you are testing whether the variable is non-empty, so you get the expected behaviour.

    0 讨论(0)
  • 2021-01-16 19:17

    Quoting. You have to quote variables that you use in [:

    $ VAR=    
    $ [ -n $VAR ]
    $ echo $?
    0
    $ [ -n "$VAR" ]
    $ echo $?
    1
    
    0 讨论(0)
提交回复
热议问题