What is the difference between the operator "!" and "-z" applied to a string?
#Example 1
if [ ! STRING ]; then ...
#Example 2
if [ -z STRING ]; then ...
Thanks
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 EXPRESSIONor[ EXPRESSION ]: this exits with the status returned byEXPRESSION
! EXPRESSION:testreturns true ofEXPRESSIONis false
-z STRING:testreturns true if the length ofSTRINGis 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 ofSTRINGis nonzero.
STRING: equivalent to-n STRINGsource:
man test
answer:[ ! STRING ] is equivalent to [ -z STRING ]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With