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 as follows, using pseudocode:
case expression in case1) statement1 statement2 ;; case2) statement1 statement2 ;; *) statement1 ;; esac
The statement layout that we see is not dissimilar to the 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 wide 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 with each item in turn. 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, which is used to evaluate grades:
#!/bin/bash #Script to evaluate grades #Usage: grade.sh stduent grade #Author: @likegeeks #Date: 1/1/1971 if [ ! $# -eq 2 ] ; then echo "You must provide <student> <grade>" exit 2 fi case ${2^^} in #Parameter expansion is used to capitalize input [A-C]) echo "$1 is a star pupil" ;; [D]) echo "$1 needs to try a little harder!" ;; [E-F]) echo "$1 could do a lot better next year" ;; *) echo "Grade could not be evaluated for $1 $2" ;; 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
Then we use parameter expansion for the value of the $2 variable to capitalize the input using ^^. This represents the grade that we supply. Since we are capitalizing the input, we first try to match against the letters A through to C.
We make similar tests for the other supplied grades, E through to F.
The following screenshot shows the script execution with different grades:
