Welcome to the next pikoTutorial!
The select
keyword in shell scripting provides an easy way to present a list of options to the user and handle their selection. It is particularly useful when you have a predefined set of choices and want the user to pick one.
#!/bin/bash
# Define menu options
options=("Option 1" "Option 2" "Option 3" "Quit")
# Prompt user with menu
PS3="Select an option: "
# Display menu using select loop
select choice in "${options[@]}"
do
case $choice in
"Option 1")
echo "You chose Option 1"
;;
"Option 2")
echo "You chose Option 2"
;;
"Option 3")
echo "You chose Option 3"
;;
"Quit")
echo "Exiting..."
break
;;
*)
echo "Invalid option! Please select a valid number."
;;
esac
done
When you run that script, you can see that all the options and prompt have been automatically printed out and you can select them in a loop:
1) Option 1
2) Option 2
3) Option 3
4) Quit
Select an option: 3
You chose Option 3
Select an option: 1
You chose Option 1
Select an option: 4
Exiting...