case statement in bash shell is similar to switch statement in C++. It can be used to test simple values like integers and characters. Bash shell checks the condition, and controls the flow of the program. The case construct also allows us to test strings against patterns that can contain wild card characters.
Syntax
Below is the syntax of case statement in shell script
case $variable-name in pattern1) ... .... ;; pattern2) ... .... ;; pattern4|pattern5|pattern6) ... .... ;; patternN) ... .... ;; *) ... .... ;; esac
$variable-name
is compared against the patterns until a match is found. *)
acts as default and it is executed if no match is found. The pattern can include wildcards. When a match is found all of the associated statements until the double semicolon (;;) are executed. esac
indicate end of case statement.
Example
Consider below example. Below example checks if user has passed any argument to this script. If the valid argument is passed, type of the vehicle is printed. |
is or operator, it matches multiple conditions.
#!/bin/bash # -z switch will test if the expansion of "$1" is a null string or not. # If it is a null string then the body is executed. if [ -z "$1" ] then echo "Unknown vehicle" exit elif [ -n $1 ] then # otherwise set first arg vehicle=$1 # use case statement to make decision case $vehicle in "car"|"van") echo "Four wheeler";; "bicycle") echo "Two wheeler";; *) echo "No match found!";; esac fi
Upon executing this script with argument it will generate below output.
./exp.sh Unknown vehicle ./exp.sh "car" Four wheeler ./exp.sh "Rail" No match found!
Interactive Script
During software installation or license agreement, we need to ask yes or no input from user. The following code snippet is one of the way to get the yes or no input from user.
#!/bin/bash echo -n "Select [yes or no]: " read yno case $yno in [yY]|[yY][Ee][Ss] ) echo "Yes" ;; [nN]|[nN][Oo] ) echo "No"; ;; *) echo "Invalid input" ;; esac
Above script ask a user to choose yes or no. If user selects ‘yes’ or ‘no’, it prints the corresponding value on the terminal. For other values entered by the user, it prints Invalid input. Below snippet shows the output of this script for some of the sample inputs.
./exp.sh Select [yes or no]: Yes Yes ./exp.sh Select [yes or no]: No No