Check if bash variable equals 0

Perlnika picture Perlnika · Oct 26, 2012 · Viewed 384.4k times · Source

I have a bash variable depth and I would like to test if it equals 0. In case yes, I want to stop executing of script. So far I have:

zero=0;

if [ $depth -eq $zero ]; then
    echo "false";
    exit;
fi

Unfortunately, this leads to:

 [: -eq: unary operator expected

(might be a bit inaccurate due to translation)

Please, how can I modify my script to get it working?

Answer

cyon picture cyon · Oct 26, 2012

Looks like your depth variable is unset. This means that the expression [ $depth -eq $zero ] becomes [ -eq 0 ] after bash substitutes the values of the variables into the expression. The problem here is that the -eq operator is incorrectly used as an operator with only one argument (the zero), but it requires two arguments. That is why you get the unary operator error message.

EDIT: As Doktor J mentioned in his comment to this answer, a safe way to avoid problems with unset variables in checks is to enclose the variables in "". See his comment for the explanation.

if [ "$depth" -eq "0" ]; then
   echo "false";
   exit;
fi

An unset variable used with the [ command appears empty to bash. You can verify this using the below tests which all evaluate to true because xyz is either empty or unset:

  • if [ -z ] ; then echo "true"; else echo "false"; fi
  • xyz=""; if [ -z "$xyz" ] ; then echo "true"; else echo "false"; fi
  • unset xyz; if [ -z "$xyz" ] ; then echo "true"; else echo "false"; fi