Certainly! Here’s a simple shell script demonstrating the use of the case statement:
#!/bin/bash
# Prompt the user to enter a choice
echo "Enter your choice:"
echo "1. Display date"
echo "2. Display current directory"
echo "3. Display system uptime"
echo "4. Exit"
# Read user input
read choice
# Case statement to perform actions based on user input
case $choice in
1)
echo "Today's date is $(date)"
;;
2)
echo "Current directory: $(pwd)"
;;
3)
echo "System uptime: $(uptime)"
;;
4)
echo "Exiting program"
exit 0
;;
*)
echo "Invalid choice"
;;
esac
Save this script as case_example.sh
and make it executable using the command chmod +x case_example.sh
.
When you run this script, it will display a menu prompting the user to enter a choice. Based on the input provided by the user, it will execute the corresponding action. If an invalid choice is entered, it will display “Invalid choice”. If the user chooses to exit, the script will terminate.