POSIX Shell Tests and Conditionals: Examples and Reference

Last updated:

WIP Alert This is a work in progress. Current information is correct but more content will probably be added in the future.

Bash in an extension over the POSIX shell, so everything that works in the POSIX shell can also be used in bash.

Tests and if-then-else constructs

The test command is present in most shells and it tests whether a boolean expression is true or false. You use it via [] expressions.

Bash and POSIX-compliant shells have also if constructs, and these are usually used together with test expressions.

The two following snippets for testing whether two variables are the same are therefore equivalent:

# using test on its own
[ "$a" -eq "$b" ] && echo 'a and b are equal'

# equivalent: using if construct
if [ "$a" -eq "$b" ]; then
  echo 'a and b are equal'
fi

Quoting

You need to place a variable within double quotes whenever there's the risk that it might contain special characters such as $, \ and so on.

Test If Two values are Equal / Different

  • to compare strings use = and !=

    foo='foo'
    
    if [ "$foo" = 'foo' ];then
      echo 'equal'
    elif [ "$foo" = 'bar' ];then
      echo 'something else'
    else
      echo 'not equal'
    fi
    
  • for booleans, use = and != also

    b1=true
    b2=false
    
    # -a means AND and -o means OR
    
    if [ $b1 = true -a $b2 = true ];then
      echo 'they are not both true'
    elif [ $b1 = false -a $b2 = true ];then
      echo 'they are not both false'
    elif [ $b1 = true -o $b2 = false ];then
      echo 'at least one of them is true'
    else
      echo 'something else'
    fi 
    
  • to compare numbers use -eq (equal) and -ne (not equal)

    # was last command a success?
    if [ "$?" -eq 0 ]; then
      echo 'great success!'
    else
      echo 'failure'
    fi 
    

Booleans

Links

Dialogue & Discussion