7

Is there any difference between the following tests?

[[ "$STRING" = "" ]] && exit 1;


[[ "x$STRING" = "x" ]] && exit 1;


[[ -z $STRING ]] && exit 1;

2 Answers 2

13

Nope, they are all the same. But couple of defensive habits to get into.

  • You should quote the $STRING in the -z one as well
  • If you are running with the -u option (I always do) then you should reference the possibly optional variable as ${STRING-} just in case its not set at all
Sign up to request clarification or add additional context in comments.

1 Comment

Why would you quote $STRING when using the [[ keyword?
1

Apparently, 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.

2 Comments

You don't need to quote $string in the -z one, and on the first example too, specially if you know that $string will contain a string.
Quoting strings is a good habit and makes a real difference if you do more complex tests like: [[ -z "$STRING" && -z "$OTHER" ]].

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.