In Bash you quite often need to check to see if a variable has been set or has a value other than an empty string. This can be done using the -n or -z string comparison operators.
The -n operator checks whether the string is not null. Effectively, this will return true for every case except where the string contains no characters. ie:
VAR="hello"
if [ -n "$VAR" ]; then
echo "VAR is not empty"
fi
Similarly, the -z operator checks whether the string is null. ie:
VAR=""
if [ -z "$VAR" ]; then
echo "VAR is empty"
fi
Note the spaces around the square brackets. Bash will complain if the spaces are not there.
What about, if the string looks empty but is not?
If I do s.th. like:
A=`some command’ # <== Returning some whitespace chars
and now
if [ -z "$z" ]; then echo Yippy; fi
it gives me always nothing in my case.
Ok, forgot the dollar symb.
Since -n is the default operation, you can also do
if [ “$VAR” ]; then
to check for a non-empty string.
[…] via Checking for empty string in Bash « timmurphy.org. […]
Thanks 🙂
Short and to the point, thanks !!!
[…] Yararlandigim kaynak. […]
Also, with -n, you must surround the variable with the double quotes.
For example, if you do:
unset var1
if [ -n $var1 ]; then
echo set
else
echo not set
fi
it will echo ‘set’. If you put the double quotes around $var1, it will echo ‘not set’
In reply to DaveVanHandel;
Any bash test without an argument will return true. Quoting the variable is required so that the test will have at least an (empty) argument, even when the variable is not set.
For example, If $a is empty (a=””), then:
if [ -n $a ]
would be the same as:
if [ -n ] (true)
There you have the -n test without arguments.
When quoted the empty variable would be treated as an argument, so:
if [ -n “$a” ],
would be the same as:
if [ -n “” ]
I ran into this issue with the file test operator (-f).