Techno World Inc - The Best Technical Encyclopedia Online!

THE TECHNO CLUB [ TECHNOWORLDINC.COM ] => Shell Script => Topic started by: Mark David on March 16, 2007, 01:30:01 PM



Title: Bourne/bash shell scripts: case statement
Post by: Mark David on March 16, 2007, 01:30:01 PM
Bourne/bash shell scripts: case statement

The case statement is an elegant replacement for if/then/else if/else statements when making numerous comparisons. This recipe describes the case statement syntax for the Bourne shells (sh, ksh, bash, zsh, etc.).

Code:
case "$var" in 
    value1)
         commands;
         ;;
    value2)
         commands;
         ;;
    *)
         commands;
         ;;
esac

The case statement compares the value of the variable ($var in this case) to one or more values (value1, value2, ...). Once a match is found, the associated commands are executed and the case statement is terminated. The optional last comparison *) is a default case and will match anything.

For example, branching on a command line parameter to the script, such as 'start' or 'stop' with a runtime control script. The following example uses the first command line parameter ($1):

Code:
case "$1" in 
     'start')
         /usr/app/startup-script
         ;;
     'stop')
         /usr/app/shutdown-script
         ;;
     'restart')
         echo "Usage: $0 [start|stop]"
         ;;
esac