Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

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'
fi

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

share|improve this question

migrated from serverfault.com Feb 4 '13 at 9:51

This question came from our site for professional system and network administrators.

2 Answers 2

if [ "$VARA" -eq 0 ] && [ "$VARB" -eq 0 ]
then echo 'both are zero, do something'
else echo 'do something else'
fi
share|improve this answer
    
Thank you, simple and clean. –  Marcos Sander Feb 3 '13 at 23:21
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 ' ' ? –  Lucas Kauffman Feb 4 '13 at 10:55
if (( var_a == 0 && var_b == 0 )); then
   # ...
fi

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

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.