Skip to content
Tutorials Center
My learning

Topics

Linux Command Reference ยท Bash Syntax

Bash select menu

Reference for the Bash select loop: print a numbered menu, read the user's choice into a variable, use REPLY and PS3, and leave the loop with break.

select builds a numbered menu from a list of words, prompts the user, and stores the chosen word in a variable. It repeats until you break out of it or input reaches end of file. It is Bash's built-in answer to "let the user pick one of these".

The menu is written to standard error, the prompt is the value of PS3, and the raw text the user typed is kept in REPLY. Because it needs input, scripts normally feed it from the terminal; in the examples below the input is supplied by a here-string.

Terminal
select name in item1 item2 item3; do
  commands
done

Try it

Bash A menu with fed input

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with read or cat), it gets the next line from this box.

Bash Menu from an array, status at end of input

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with read or cat), it gets the next line from this box.

Syntax

Terminal
select name [in word ...]; do list; done
Part Description
name Variable set to the word whose number was entered, or to empty if the input was not a valid number.
in word ... The items. Without in, the positional parameters are listed.
PS3 The prompt shown before reading (default #? ).
REPLY Always holds the exact line the user typed.
COLUMNS Controls how many menu columns are used.

Returns: 1 when the loop ends because input reached end of file; after a break, the status of the last command that ran.

Usage notes

  • The loop does not end by itself after a valid choice; it shows the prompt again. Use break (or exit) in the body for the success path.
  • If the input is not a number in the menu range, name is set to the empty string. Test for that and print a message; the loop then shows the prompt again.
  • If the user enters an empty line, the menu is shown again without running the body.
  • The menu and prompt go to standard error, the choice is read from standard input. In scripts, 2>&1 or redirects change this.
  • Quote array expansions ("${items[@]}") so that items with spaces remain one entry each.
  • Setting PS3 is almost always needed; the default prompt #? is not helpful.
  • select is for interactive use. For scripts that run unattended, take choices from arguments or environment variables instead, and use case to dispatch.
  • Pressing Ctrl-D (end of file) ends the loop. It is not available in a plain POSIX sh.