select
select creates a loop that lets the user interactively choose from a numbered menu. The menu is displayed automatically, and the body of the loop runs based on the number the user enters. Use it when you need a simple interactive menu in a shell script.
Syntax
Basic syntax.
select variable in item_list; do
commands ($variable holds the selected value)
break # Use break explicitly to exit the loop
done
Change the prompt string (default is "#? ").
PS3="Choose an option: "
select variable in item_list; do
commands
done
Related Variables and Behaviors
| Variable / Behavior | Description |
|---|---|
| $REPLY | Contains the number the user typed (the selected index). |
| $variable | Contains the text of the menu item the user selected. |
| PS3 | The prompt string shown before each input (default is #? ). |
| break | Exits the select loop. Without break, the menu is displayed again after each selection. |
| Out-of-range number | $variable is set to an empty string. You can check for this with if to show an error. |
| Empty input (Enter only) | Redisplays the menu. |
Sample Code
Combine select with case to build an interactive menu. Use PS3 to customize the prompt string.
menu.sh
#!/bin/bash
PS3="Choose an action: "
select action in "List files" "Show current directory" "Show date" "Quit"; do
case "$action" in
"List files")
ls -la
;;
"Show current directory")
pwd
;;
"Show date")
date
;;
"Quit")
echo "Exiting."
break
;;
*)
echo "Invalid selection (input: $REPLY)"
;;
esac
done
bash menu.sh
1) List files
2) Show current directory
3) Show date
4) Quit
Choose an action: 2
/home/alice/project
Choose an action: 4
Exiting.
Generate a menu from an array and handle invalid number input.
lang_select.sh
PS3="Select a language: "
languages=("Bash" "Python" "PHP" "Kotlin" "Cancel")
select lang in "${languages[@]}"; do
if [[ -z "$lang" ]]; then
echo "Invalid number."
continue
fi
if [[ "$lang" = "Cancel" ]]; then
echo "Cancelled."
break
fi
echo "Selected language: $lang (number: $REPLY)"
break
done
bash lang_select.sh
1) Bash
2) Python
3) PHP
4) Kotlin
5) Cancel
Select a language: 3
Selected language: PHP (number: 3)
Notes
select works like a while loop internally — it keeps displaying the menu until you explicitly run break or the user presses Ctrl+D (EOF).
select cannot be used in non-interactive contexts such as pipelines or cron jobs. Only use it when user interaction is expected. For non-interactive environments, design your script to accept command-line arguments instead.
For handling command-line arguments, special variables $1–$9 and case statements are useful.
If you find any errors or copyright issues, please contact us.