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...