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

Pavol Kutaj

--

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
I’ve never used `PS3`; only ‘read’ for input. What’s happening?
  • The PS3 variable is set to customize the prompt displayed before the list of choices in a select construct.
  • When the select statement is executed, it uses the value of PS3 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 with select 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 a select construct and is tailored for menu prompts.
  • select provides a concise and convenient way to create menus in bash scripts with predefined options.

--

--

Pavol Kutaj

Today I Learnt | Infrastructure Support Engineer at snowplow.io with a passion for cloud infrastructure/terraform/python/docs. More at https://pavol.kutaj.com