Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking for null string in bash

Tags:

linux

bash

Is there any difference between the following tests?

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


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


[[ -z $STRING ]] && exit 1;
like image 588
Šimon Tóth Avatar asked Jul 12 '11 14:07

Šimon Tóth


People also ask

How do I check if a string is empty in bash?

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.

What is a null string in bash?

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.

Is there null in bash?

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 .

What does [- Z $1 mean in bash?

$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.


2 Answers

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
like image 66
Sodved Avatar answered Nov 14 '22 23:11

Sodved


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.

like image 20
Guilherme David da Costa Avatar answered Nov 14 '22 21:11

Guilherme David da Costa