45

I don't set any values for $pass_tc11; so it is returning null while echoing. How to compare it in if clause?

Here is my code. I don't want "Hi" to be printed...

-bash-3.00$ echo $pass_tc11

-bash-3.00$ if [ "pass_tc11" != "" ]; then
> echo "hi"
> fi
hi
-bash-3.00$
codeforester
  • 39,467
  • 16
  • 112
  • 140
logan
  • 7,946
  • 36
  • 114
  • 185
  • 2
    There is a difference between a variable being empty and a variable being unset. From the question's title, this appears to be the distinction you are trying to make, but it is unclear from the question if indeed you care (or are even aware of) this distinction. Do you care about that distinction? If so `test -z` will not help. – William Pursell Jan 28 '14 at 14:12

2 Answers2

90

First of all, note you are not using the variable correctly:

if [ "pass_tc11" != "" ]; then
#     ^
#     missing $

Anyway, to check if a variable is empty or not you can use -z --> the string is empty:

if [ ! -z "$pass_tc11" ]; then
   echo "hi, I am not empty"
fi

or -n --> the length is non-zero:

if [ -n "$pass_tc11" ]; then
   echo "hi, I am not empty"
fi

From man test:

-z STRING

the length of STRING is zero

-n STRING

the length of STRING is nonzero

Samples:

$ [ ! -z "$var" ] && echo "yes"
$

$ var=""
$ [ ! -z "$var" ] && echo "yes"
$

$ var="a"
$ [ ! -z "$var" ] && echo "yes"
yes

$ var="a"
$ [ -n "$var" ] && echo "yes"
yes
fedorqui
  • 275,237
  • 103
  • 548
  • 598
  • 1
    @logan, `man test` is the man page to check file types and compare values. – fedorqui Jan 28 '14 at 13:50
  • @logan I think it can be good to use `-z` for this case. It can be more clear for the one reading the code that you want to see if the var is empty. I would leave the string comparison for the cases in which you are comparing with a non-empty string. – fedorqui Jan 28 '14 at 13:55
  • Why do we need quoted $var, "$var"? Why $var does not work in if test? – CoR Nov 12 '20 at 15:20
  • 1
    @CoR it is good to get used to quoting in all cases, to prevent then having situations like `v="aa bb"; [ ! -z $v ] && echo "yes"` that gives a _-bash: [: aa: binary operator expected_ error. – fedorqui Nov 12 '20 at 15:26
2

fedorqui has a working solution but there is another way to do the same thing.

Chock if a variable is set

#!/bin/bash
amIEmpty='Hello'
# This will be true if the variable has a value
if [ $amIEmpty ]; then
    echo 'No, I am not!';
fi

Or to verify that a variable is empty

#!/bin/bash      
amIEmpty=''
# This will be true if the variable is empty
if [ ! $amIEmpty ]; then
    echo 'Yes I am!';
fi

tldp.org has good documentation about if in bash:
http://tldp.org/LDP/Bash-Beginners-Guide/html/sect_07_01.html

espr
  • 21
  • 1
  • 1
    Hmmm. Fails if you do `amIEmpty='b < a'`. You need to quote the test: `if [ "$amIEmpty" ] …`. (I _much_ prefer the `-n`.) – bobbogo Jan 28 '14 at 17:22