Case



next up previous contents index
Next: Unix Commands inside Up: Shell Programs (Scripts) Previous: If-Then-Else

Case

While we may use a series of if-then-else constructs to test a variable against several forms, it is much easier to use the case statement. This is done in the first script below. In the second script we use wild-card matches with the case statement. This takes one argument and matches it against several patterns in the case statement. If the pattern matches the argument, then the script prints out a statement:


case $key in Match the variable $key. pattern1) Test match to pattern1. statement If $key matches pattern1, then execute statement. ;; Each pattern ends with ;;. pattern2) Test match to pattern2. statement If match, then execute statement. ;; esac Close the case with esac.


#!/bin/sh case $1 in Match the first argument. in.date) echo "Argument is in.date." ;; *.f) Matches anything that ends in .f. echo "Argument is a Fortran file name." ;; *.c) Matches anything that ends in .c. echo "Argument is C file." ;; in|out) Use | for 'or' echo "Argument is either the word in or the word out." ;; *) This will match anything. echo "Argument does not match any the patterns." ;; esac



next up previous contents index
Next: Unix Commands inside Up: Shell Programs (Scripts) Previous: If-Then-Else