This article explains using case statements in shell scripts to simplify menu-driven program logic.
In this lesson, we explore how to use case statements in shell scripts to simplify the logic of a menu-driven program. Previously, we combined a while loop with an if-elif-else construct to handle user choices. Although that approach works, using a case statement makes your code simpler, more readable, and easier to manage.
The same functionality can be achieved more elegantly using a case statement. The structure of a case statement starts with the case keyword and ends with esac (which is “case” spelled backward). Each branch of the case block ends with a double semicolon (;;), and the special pattern * serves as a catch-all, similar to an else block.
Copy
Ask AI
echo "1. Shutdown"echo "2. Restart"echo "3. Exit Menu"read -p "Enter your choice: " choicecase $choice in 1) shutdown now ;; 2) shutdown -r now ;; 3) break ;; *) continue ;;esac
Using a case statement not only simplifies the code but also improves its readability and maintenance, especially when dealing with multiple conditions.
Here is a more comprehensive version of the menu-driven program that uses a while loop together with a case statement:
Copy
Ask AI
while truedo echo "1. Shutdown" echo "2. Restart" echo "3. Exit Menu" read -p "Enter your choice: " choice case $choice in 1) shutdown now ;; 2) shutdown -r now ;; 3) break ;; *) continue ;; esacdone
This approach drastically simplifies the flow of the program compared to using numerous if and elif statements. If you are familiar with programming languages like C, you will notice that the case statement resembles the switch statement, making it easier to understand and implement.Practice incorporating case statements into your shell scripts to reinforce the concepts presented and enhance your scripting skills.