The case statement is often used when more than two outcomes are possible. Here is the syntax:
case $VARIABLE in
value_1) commands for specified value_1 ;;
value_2) commands for specified value_2 ;;
value_3) commands for specified value_3 ;;
*) commands for value not matching any specified choices ;;
The $VARIABLE is compared against the values until a match is found. If a match is found, the associated commands are executed and the case statement is terminated. If the value the user enters doesn’t match any of the choices specified in the case statement, the *) characters start the code portion that runs in this situation. esac indicates the end of the case statement.
Consider the following example.
echo “Select your choice:”
echo “Press 1 to display your current directory”
echo “Press 2 to display the current date and time”
echo “Press 3 to list the content of the current directory”
case $CHOICE in
3) ls -l;;
*) echo Invalid selection;;
In the example above, you can see that the user can select whether he/she wants to display the current directory, the current time, or list the directory content. If the user enters a value that doesn’t equal 1, 2, or 3, the Invalid selection message will be displayed: