select and interactive menus
select choice in words; do commands; done is a Bash menu construct. Bash numbers the expanded items and displays the menu and PS3 prompt on standard error. It reads a line from standard input. A valid menu number sets choice to the corresponding item; an invalid nonempty entry sets it to an empty string. REPLY keeps the entered line. An empty input line redisplays the menu without executing the body. EOF ends the menu; a break also ends it. Use explicit choices and handle invalid input; an empty selection can be ambiguous if empty strings are allowed as menu items, so avoid them in simple menus. select is not POSIX sh syntax. For repeatable tests below, printf supplies predetermined input via process substitution and stderr is captured separately rather than depending on a real terminal. In Bash 5.2, immediate EOF with a nonempty menu prints a newline to stdout and returns status 1 from select. The final printf in example 3 returns 0, so that example does not report the menu status. Save $? immediately after select if that status matters.
Practical examples
Run each example separately in a fresh Bash 5.2 process and empty practice directory. Tests use C locale; do not enter expected output as code.
Choose a numbered entry
PS3='Choose: 'select choice in Start Quit; do printf 'choice=%s reply=%s\n' "$choice" "$REPLY" breakdone < <(printf '2\n')Expected stdout:
choice=Quit reply=2Expected stderr (menu prompt):
1) Start2) QuitChoose: The menu and prompt go to stderr, while the result goes to stdout.
Reject an invalid choice
PS3='Choose: 'select choice in Start Quit; do if [[ -z $choice ]]; then printf 'invalid=%s\n' "$REPLY" continue fi printf 'choice=%s\n' "$choice" breakdone < <(printf '9\n1\n')Expected stdout:
invalid=9choice=StartExpected stderr (menu prompt):
1) Start2) QuitChoose: Choose: An invalid number produces an empty choice; the next valid number is accepted.
Finish at EOF
PS3='Choose: 'select choice in Start Quit; do printf '%s\n' "$choice"done < /dev/nullprintf '%s\n' finishedExpected stdout:
finishedExpected stderr (menu prompt):
1) Start2) QuitChoose: The menu prints, but no selection is read before EOF. Bash 5.2 also prints a blank line on stdout at EOF.
Common mistakes
Do not treat REPLY as the selected label. It holds the entered text, which may be invalid. Do not evaluate it as shell code or arithmetic.
Practice
Create a menu with Start and Quit, handle invalid choices, and exit on Quit or EOF. Feed 9 then 2 from a prepared input file; verify that 9 is rejected and Quit is selected. Try interactively only after this test.
Next: Read lines and NUL-separated records