Multiple expression if statement in BASH
It’s not very well documented, but it’s possible to include multiple conditional expressions in a single if statement in BASH. By multiple conditional expressions, I mean something like:
if foo = 1 or bar = 3 or abc = 4 then
print Hello World
end if
You can do boolean OR in BASH by using the -o operator. The following is the above code written in BASH:
if [ $foo -eq 1 -o $bar -eq 3 -o $abc -eq 4 ]; then
echo Hello World
fi
For boolean AND, use the -a operator. You can also intermix the two.
Tags:
- none
This entry was posted on Tuesday, November 21st, 2006 at 12:34 am and is filed under programming. You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.
Durand Says:
December 14th, 2007 at 5:18 pm
Thanks, that was very useful
simon Says:
January 12th, 2008 at 1:52 pm
Quite useful since I googled “bash if” and your explanation was exactly what I needed!
dave Says:
January 22nd, 2008 at 9:38 pm
Thanks helped me solve my && || bools
David Says:
February 25th, 2008 at 3:13 pm
You can intermix the two, but how does it flow? IOW, if I say
if [ $foo -eq 1 -o $bar -eq 1 -a $abc -eq 1 ]
does that mean that either $foo or $bar can be 1 but $abc must be 1? Or does it mean that either $foo can be 1 or $bar and $abc can be 1?
Ian Stevens Says:
February 25th, 2008 at 11:54 pm
In this case, both $bar and $abc must be 1, regardless of the value of $foo.
Tony Says:
August 5th, 2008 at 1:23 pm
Great help Ian!
Another evaluation that might be hepful…
Let say you supposed to have two environment variables $A and $B(A and B could be files as well), you want to know if those values are set or not, you can use
if [ -z $A -a -z $B ];
then
echo “Please define A and B”
fi
this is useful when you have many conditions to evaluate
Rechosen Says:
August 6th, 2008 at 12:41 pm
According to tldp.org, the -a (for and) operator has precedence over -o (for or), which means that -a is evaluated and processed before -o. The following experiment shows it:
foo=1
bar=2
if [ $foo -eq 2 -a $bar -eq 2 -o $bar -eq 1 ]; then
echo “Or has precedence.”
else
echo “And has precedence.”
fi
The above returns “And has precedence.”
stef Says:
August 12th, 2008 at 8:21 am
I concur, the logical AND always has precedence before the logical OR. Basic math logic that you learn in high school 4th year i think.
See ya!