Is there any difference between the following tests?
[[ "$STRING" = "" ]] && exit 1;
[[ "x$STRING" = "x" ]] && exit 1;
[[ -z $STRING ]] && exit 1;
To check if string is empty in Bash, we can make an equality check with the given string and empty string using string equal-to = operator, or use -z string operator to check if the size of given string operand is zero.
A "null string" is one which has zero length. In your example, both are the same. A simple test: #!/bin/bash go(){ local empty local empty2="" [[ -z $empty ]] && echo "empty is null" [[ -z $empty2 ]] && echo "empty2 is null" [[ $empty == $empty2 ]] && echo "They are the same" } go.
As defined in the Bash manual the null command : is a command builtin that will do nothing and will always succeed. The command exit status will always be 0 .
$1 means an input argument and -z means non-defined or empty. You're testing whether an input argument to the script was defined when running the script.
Nope, they are all the same. But couple of defensive habits to get into.
$STRING
in the -z
one as well${STRING-}
just in case its not set at allApparently, they all do the same thing, that is check if the given string its "empty", except that the first one checks if $string its empty, the second checks whether x plus $string its equals to x and finally, -z that checks the length. Personally I'd ratter go with -z that's more realiable.
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