I am trying to write a single IF statement which can check two variables at once.

I have two variables, for example: $VARA $VARB

Both with either contain a 0 or a non 0 value. I need an if statement which can check both and if either are not equal to 0, if will perform an action, if both are 0 if will perform a different action.

With a single variable, I can do this:

if [ $VARA -ne 0 ]
then echo 'The operation failed! VARA is not equal to 0'
else echo 'The operation suceeded! VARA is equal to 0'

However, I am not sure how to check both VARA and VARB at the same time. Thank you.

if [ "$VARA" -eq 0 ] && [ "$VARB" -eq 0 ]
then echo 'both are zero, do something'
else echo 'do something else'
  • 1
    Could even use the -a syntax if [ $VARA -eq 0 -a $VARB -eq 0 ]; then.... -a is and and -o is or.
    – lsd
    Feb 4 '13 at 1:14
  • 1
    Likewise, the && can be replaced with || in circumstances where you need to use a logical or instead of and. While -a and -o can also be used to avoid the usage of multiple [] pairs, some people prefer the method Lucas cited for the sake of readability.
    – Andrew B
    Feb 4 '13 at 2:58
  • 2
    This will break if $VARA or $VARB are more than two words long under wordsplitting. They should be quoted appropriately.
    – Chris Down
    Feb 4 '13 at 10:02
  • @ChrisDown what do you mean? like putting the vars between ' ' ? Feb 4 '13 at 10:55
  • @LucasKauffman: Like putting the vars between " double quotes. Single quotes will not work, as they will prevent variable expansion.
    – tripleee
    Feb 4 '13 at 19:25
if (( var_a == 0 && var_b == 0 )); then
   # ...

In Bash, always use (( ... )) for arithmetic evaluations.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy