DEV Community

Cover image for Simple menus in Bash scripts with select
pikoTutorial
pikoTutorial

Posted on • Originally published at pikotutorial.com

Simple menus in Bash scripts with select

Welcome to the next pikoTutorial!

The select command 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
Enter fullscreen mode Exit fullscreen mode

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...
Enter fullscreen mode Exit fullscreen mode

Top comments (0)