Bash Script to Create a Menu Driven Program
while loop and case statement to display a menu and handle user choices, like: while true; do echo "1) Option1"; read choice; case $choice in 1) echo "You chose 1";; 2) exit;; *) echo "Invalid option";; esac; done.Examples
How to Think About It
case statement to run code based on the choice. Keep looping until the user chooses to exit.Algorithm
Code
#!/bin/bash while true; do echo "Menu:" echo "1) Say Hello" echo "2) Exit" read -p "Enter choice: " choice case $choice in 1) echo "Hello!";; 2) echo "Exiting program."; break;; *) echo "Invalid option, please try again.";; esac done
Dry Run
Let's trace choosing option 1, then invalid option 3, then exit with 2.
Show menu and read input
Menu displayed, user inputs '1'
Process choice 1
Prints 'Hello!' and loops back
Show menu and read input
Menu displayed, user inputs '3'
Process invalid choice
Prints 'Invalid option, please try again.' and loops back
Show menu and read input
Menu displayed, user inputs '2'
Process exit choice
Prints 'Exiting program.' and breaks loop
| Step | User Input | Output |
|---|---|---|
| 1 | 1 | Hello! |
| 2 | 3 | Invalid option, please try again. |
| 3 | 2 | Exiting program. |
Why This Works
Step 1: Loop for continuous menu
The while true loop keeps the menu running until the user chooses to exit.
Step 2: Reading user input
The read command waits for the user to enter their choice.
Step 3: Handling choices with case
The case statement matches the input to options and runs the corresponding commands.
Step 4: Exiting the loop
When the user selects the exit option, break stops the loop and ends the program.
Alternative Approaches
#!/bin/bash PS3='Choose an option: ' select opt in "Say Hello" "Exit"; do case $opt in "Say Hello") echo "Hello!";; "Exit") echo "Exiting program."; break;; *) echo "Invalid option.";; esac done
#!/bin/bash
say_hello() { echo "Hello!"; }
while true; do
echo "1) Say Hello"
echo "2) Exit"
read -p "Enter choice: " choice
case $choice in
1) say_hello;;
2) echo "Exiting program."; break;;
*) echo "Invalid option.";;
esac
doneComplexity: O(n) time, O(1) space
Time Complexity
The loop runs until the user exits, so time depends on user input count, making it O(n) where n is number of interactions.
Space Complexity
Uses constant space for variables and no extra data structures, so O(1).
Which Approach is Fastest?
All approaches run quickly; using select is simpler but less flexible, while functions improve code clarity without affecting speed.
| Approach | Time | Space | Best For |
|---|---|---|---|
| while + case loop | O(n) | O(1) | Simple, flexible menus |
| select command | O(n) | O(1) | Quick menu creation with less code |
| functions for options | O(n) | O(1) | Organized code for complex menus |
read -p to prompt and get user input on the same line for cleaner menus.