How to Make Menus in Bash with ‘select’
The aim of this page📝 is to explain the usage of the PS3
variable in conjunction with the select
construct in bash scripting based on the particular example of creating a menu to choose a favorite vegetable. My notes for Advanced Bash Scripting
2 min readApr 26, 2024
- The code below makes a nice menu. Python does not have this OOTB, see How to Create a Simple Menu Maker for Python Scripts
echo "Example 11-30. Creating menus using select"
PS3="Choose your favorite vegetable: "
echo
select vegetable in "beans" "carrots" "potatoes" "onions" "rutabagas"; do
echo
echo "Your favorite veggie is ${vegetable}"
echo "Yuck!"
echo
break
done
- The
PS3
variable is set to customize the prompt displayed before the list of choices in aselect
construct. - When the
select
statement is executed, it uses the value ofPS3
as the prompt for user input. - The
select
construct simplifies creating menus by handling menu display, user input, and option selection. PS3
is designed to be used exclusively withselect
and is not used for general user input prompts.- Using
read
for menu-like functionality would require more manual handling of input validation and display. select
automates menu creation tasks, making it easier to implement a menu-driven interface.select
validates user input against the list of options and assigns the selected option to a variable.PS3
is not used outside of aselect
construct and is tailored for menu prompts.select
provides a concise and convenient way to create menus in bash scripts with predefined options.