Case statements in BASH

The case construct in bash shell allows us to test strings against patterns that can contain wild card characters. Bash case statement is the simplest form of the bash if-then-else statement.

Syntax of bash case statement.

case expression in
    pattern1 )
        statements ;;
    pattern2 )
        statements ;;
    ...
esac

Following are the key points of bash case statements:

  • Case statement first expands the expression and tries to match it against each pattern.
  • When a match is found all of the associated statements until the double semicolon (;;) are executed.
  • After the first match, case terminates with the exit status of the last command that was executed.  So All wildcards MUST go towards the end of the Case statement
  • If there is no match, exit status of case is zero.

5 Bash Case Statement Examples