Skip to main content

Documentation Index

Fetch the complete documentation index at: https://docs.syntblaze.com/llms.txt

Use this file to discover all available pages before exploring further.

The select construct is a specialized loop in Bash used to generate numbered, interactive menus from a sequence of words. It automates the process of presenting options to standard error (stderr), reading user input from standard input (stdin), and mapping that input to a specific variable for evaluation within the loop body.
select variable_name in word_list
do
    # commands to execute
done

Execution Mechanics

  1. Menu Generation: Bash expands word_list into a set of discrete items. It prints these items to stderr, formatting them in columns and prefixing each with a sequential integer starting from 1.
  2. Prompting: Bash displays the prompt string defined by the PS3 environment variable. If PS3 is unset, it defaults to #? .
  3. Input Handling: The shell reads a line of input from stdin.
  4. Variable Assignment:
    • If the input evaluates to a valid integer corresponding to an item in the generated menu, variable_name is assigned the string value of that item.
    • If the input is invalid (out of bounds or non-numeric), variable_name is set to null (empty).
    • In all cases, the raw, unparsed user input is assigned to the built-in REPLY variable.
  5. Iteration: After executing the commands within the do...done block, the select loop prompts the user again. It is an infinite loop by default and requires an explicit control statement (such as break, return, or exit) or an EOF signal (Ctrl+D) to terminate.

Syntactic Nuances

  • Omitted Word List: If the in word_list clause is omitted (i.e., select variable_name; do...), the loop defaults to iterating over the current positional parameters ("$@"), identical to the behavior of a for loop with an omitted list.
  • Empty Input: If the user presses Enter without providing any input, Bash automatically reprints the numbered menu and the PS3 prompt before waiting for input again. The loop body is not executed in this scenario.
  • Internal Field Separator (IFS): The expansion of word_list is subject to word splitting based on the IFS variable. Quoting elements in the word_list is necessary to preserve whitespace within individual menu items.
Master Bash with Deep Grasping Methodology!Learn More