0
0
Bash-scriptingHow-ToBeginner · 3 min read

How to Use select in Bash: Simple Menu Selection Guide

In Bash, the select command creates a simple numbered menu from a list of options and waits for the user to choose one. It automatically displays the options and stores the selected value in a variable for easy use in scripts.
📐

Syntax

The basic syntax of select is:

  • select variable in list: Defines the menu options and the variable to store the choice.
  • do ... done: Contains commands to run after a selection is made.
  • break: Usually used to exit the menu loop after a valid choice.
bash
select choice in option1 option2 option3
  do
    echo "You selected $choice"
    break
  done
💻

Example

This example shows a menu with three fruits. The user picks one by typing its number, and the script prints the chosen fruit.

bash
#!/bin/bash

select fruit in Apple Banana Cherry
 do
   if [ -n "$fruit" ]; then
     echo "You selected $fruit"
     break
   else
     echo "Invalid selection. Try again."
   fi
 done
Output
1) Apple 2) Banana 3) Cherry #? 2 You selected Banana
⚠️

Common Pitfalls

Common mistakes when using select include:

  • Not checking if the user input is valid, which can cause empty or unexpected values.
  • Forgetting to use break to exit the loop, causing the menu to repeat endlessly.
  • Using select outside a loop, which prevents multiple attempts.
bash
select choice in A B C
 do
   echo "You selected $choice"
 done

# This will loop forever without validation or exit.

# Correct way:
select choice in A B C
 do
   if [ -n "$choice" ]; then
     echo "You selected $choice"
     break
   else
     echo "Invalid choice, try again."
   fi
 done
📊

Quick Reference

CommandDescription
select variable in listCreates a numbered menu from the list and stores choice in variable
do ... doneBlock of commands executed after user selects an option
breakExits the select loop after a valid selection
$REPLYStores the raw user input number
$variableStores the selected item from the list

Key Takeaways

Use select to create simple interactive menus in Bash scripts.
Always validate the user’s choice to handle invalid input gracefully.
Use break to exit the menu loop after a valid selection.
The variable after select holds the chosen item, while $REPLY holds the raw input number.
Place select inside a loop to allow multiple attempts until a valid choice is made.