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?
You can try this:
NOTE: Here it's just
?
afterdepth
.or
NOTE: Here it's
:?
afterdepth
.Here if the variable
depth
is foundnull
it will print the error message and then exit.Double parenthesis
(( ... ))
is used for arithmetic operations.Double square brackets
[[ ... ]]
can be used to compare and examine numbers (only integers are supported), with the following operators:For example
Try:
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.An unset variable used with the
[
command appears empty to bash. You can verify this using the below tests which all evaluate totrue
becausexyz
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
you can also use this format and use comparison operators like '==' '<='
Specifically:
((depth))
. By example, the following prints1
.