Bash operators: “!” vs “-z”

后端 未结 2 1135

What is the difference between the operator \"!\" and \"-z\" applied to a string?

#Example 1
if [ ! STRING ]; then ...

#Example 2
if [ -z STRING ]; then ...         


        
相关标签:
2条回答
  • 2020-12-21 08:05

    First of all you make use of single brackets. This implies that you are using the test command and not the Bash-builtin function. From the manual :

    test EXPRESSION or [ EXPRESSION ]: this exits with the status returned by EXPRESSION

    ! EXPRESSION: test returns true of EXPRESSION is false

    -z STRING: test returns true if the length of STRING is zero.

    Examples:

    $ [ -z "foo" ] && echo "zero length" || echo "non-zero length"
    non-zero length
    $ [ ! -z "foo" ] && echo "non-zero length" || echo "zero length"
    non-zero length
    $ [ -z "" ] && echo "zero length" || echo "non-zero length"
    zero length
    $ [ ! -z "" ] && echo "non-zero length" || echo "zero length"
    zero length
    

    But now you were wondering about [ ! STRING ]:

    The manual states that [ STRING ] is equivalent to [ -n STRING ], which tests if STRING has a non-zero length. Thus [ ! STRING ] is equivalent to [ -z STRING ].

    -n STRING: the length of STRING is nonzero.

    STRING: equivalent to -n STRING

    source: man test


    answer:[ ! STRING ] is equivalent to [ -z STRING ]

    0 讨论(0)
  • 2020-12-21 08:16

    Short answer: they're the same.


    [ ! STRING ]
    

    is the negation of

    [ STRING ] # which is implicitly [ -n STRING ]
    

    so [ ! STRING ] is true if the the length of STRING is not non-zero.

    [ -z STRING ]
    

    is also true if the length of STRING is zero.

    0 讨论(0)
提交回复
热议问题