Using case statements

Rather than using multiple elif statements, a case statement may provide a simpler mechanism when evaluations are made on a single expression.

The basic layout of a case statement is listed below using pseudo-code:

case expression in
 case1) 
  statement1
  statement2
 ;;
 case2)
  statement1
  statement2
 ;;
 *)
  statement1
 ;;
esac

The statement layout that we see is not dissimilar to switch statements that exist in other languages. In bash, we can use the case statement to test for simple values, such as strings or integers. Case statements can cater for a side range of letters, such as [a-f] or a through to f, but they cannot easily deal with integer ranges such as [1-20].

The case statement will first expand the expression and then it will try to match it in turn with each item. When a match is found, all the statements are executed until the ;;. This indicates the end of the code for that match. If there is no match, the case else statement indicated by the * will be matched. This needs to be the last item in the list.

Consider the following script grade.sh, used to evaluate grades:

#!/bin/bash
# Script to evaluate grades
# Usage: grade.sh student grade
# Author: @theurbanpenguin
# Date: 1/1/1971
if [ ! $# -eq2 ] ; then
echo "You must provide <student><grade>
exit 2
fi
case $2 in
  [A-C]|[a-c]) echo "$1 is a star pupil"
  ;;
  [Dd]) echo "$1 needs to try a little harder!"
  ;;
  [E-F]|[e-f]) echo "$1 could do a lot better next year"
  ;;
  *) echo "Grade could not be evaluated for $1"
esac

The script first uses an if statement to check that exactly two arguments have been supplied to the script. If they are not supplied, the script will exit with an error state:

if [ ! $# -eq2 ] ; then
echo "You must provide <student><grade>
exit 2
fi

The case statement then expands the expression, which is the value of the $2 variable in this example. This represents the grade that we supply. We then try to match first against the letters A through to C in both upper-case and lower-case. [A-C] is used to match A or B or C. The vertical bar then adds an additional OR to compare with a, b, or c:

[A-C]|[a-c]) echo "$1 is a star pupil"
;;

We make similar tests for other supplied grades A through to F.

The following screenshot show the script execution with different grades:

Using case statements
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.14.247.117