POSIX Shell Tests and Conditionals: Examples and Reference

POSIX Shell Tests and Conditionals: Examples and Reference

Last updated:
Table of Contents

Bash vs POSIX Shell

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

Tests VS if then

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

If-then-else syntax

Note that the symbol for equality is a single equals operator:

#!/usr/bin/env sh

if [ -f myfile.txt ]; then
  cat myfile.txt
elif [ -f otherfile.txt ]; then
  cat otherfile.txt
elif [ "foo" = "bar" ]; then
  echo "this will never be run!"
else 
  echo "files not found!" 
fi

One-line if-then

TEMPLATE: if condition; then action; fi;

EXAMPLE: echo "foo" if a file exists

if [ -f file.txt ]; then echo "exists"; fi;

One-line if-then-else

TEMPLATE: if condition; then action1; else action2; fi;

EXAMPLE: echo "foo" if a file exists, echo "bar" if it doesn't

if [ -f file.txt ]; then echo "foo"; else echo "bar"; 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 
    

References