Contents / Previous / Next


Case Statement

The case statement allows us to specify several possible
statement blocks depending on the value of a variable.

The case statement can replace a group of "if" statements.
Example (process the first argument to a program): #!/bin/sh case $1 in --test|-t) echo "you used the --test option" exit 0 ;; --help|-h) echo "Usage:" echo " myprog.sh [--test|--help|--version]" exit 0 ;; --version|-v) echo "myprog.sh version 0.0.1" exit 0 ;; -*) echo "No such option $1" echo "Usage:" echo " myprog.sh [--test|--help|--version]" exit 1 ;; esac echo "You typed \"$1\" on the command-line" Each statement block is separated by ;;.

The strings before the ) are glob expression matches.
The first successful match causes the following blocks to be executed.
The | symbol enables us to enter several possible glob expressions.