How to Use select in Bash: Simple Menu Selection Guide
In Bash, the
select command creates a simple numbered menu from a list of options and waits for the user to choose one. It automatically displays the options and stores the selected value in a variable for easy use in scripts.Syntax
The basic syntax of select is:
select variable in list: Defines the menu options and the variable to store the choice.do ... done: Contains commands to run after a selection is made.break: Usually used to exit the menu loop after a valid choice.
bash
select choice in option1 option2 option3
do
echo "You selected $choice"
break
doneExample
This example shows a menu with three fruits. The user picks one by typing its number, and the script prints the chosen fruit.
bash
#!/bin/bash select fruit in Apple Banana Cherry do if [ -n "$fruit" ]; then echo "You selected $fruit" break else echo "Invalid selection. Try again." fi done
Output
1) Apple
2) Banana
3) Cherry
#? 2
You selected Banana
Common Pitfalls
Common mistakes when using select include:
- Not checking if the user input is valid, which can cause empty or unexpected values.
- Forgetting to use
breakto exit the loop, causing the menu to repeat endlessly. - Using
selectoutside a loop, which prevents multiple attempts.
bash
select choice in A B C do echo "You selected $choice" done # This will loop forever without validation or exit. # Correct way: select choice in A B C do if [ -n "$choice" ]; then echo "You selected $choice" break else echo "Invalid choice, try again." fi done
Quick Reference
| Command | Description |
|---|---|
| select variable in list | Creates a numbered menu from the list and stores choice in variable |
| do ... done | Block of commands executed after user selects an option |
| break | Exits the select loop after a valid selection |
| $REPLY | Stores the raw user input number |
| $variable | Stores the selected item from the list |
Key Takeaways
Use
select to create simple interactive menus in Bash scripts.Always validate the user’s choice to handle invalid input gracefully.
Use
break to exit the menu loop after a valid selection.The variable after
select holds the chosen item, while $REPLY holds the raw input number.Place
select inside a loop to allow multiple attempts until a valid choice is made.