crazed monkey

Ian Stevens’ weblog

RSS

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.

5 Responses to “Multiple expression if statement in BASH”

  1. Durand Says:

    December 14th, 2007 at 5:18 pm

    Thanks, that was very useful

  2. simon Says:

    January 12th, 2008 at 1:52 pm

    Quite useful since I googled “bash if” and your explanation was exactly what I needed!

  3. dave Says:

    January 22nd, 2008 at 9:38 pm

    Thanks helped me solve my && || bools

  4. 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?

  5. 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.

Leave a Reply