Linux Basic — select Statement
select Statement
select builds a numbered menu from a list of words and reads the chosen value into a variable. It’s ideal for small interactive utilities.
Basic Usage
PS3='Choose an option: '
select opt in "Install" "Upgrade" "Remove" "Quit"; do
case "$REPLY" in
1) echo "installing"; break;;
2) echo "upgrading"; break;;
3) echo "removing"; break;;
4) echo "bye"; exit 0;;
*) echo "invalid";;
esac
done
$optgets the chosen word (or empty if invalid)$REPLYis the numeric choicePS3sets the prompt shown before each iteration
Use with Arrays
options=("start" "stop" "status" "quit")
PS3='action> '
select action in "${options[@]}"; do
[[ -n "$action" ]] || { echo "invalid"; continue; }
echo "you chose $action"
[[ "$action" == "quit" ]] && break
done
This is cleaner when choices are dynamic.
Handling EOF and Interrupts
Ctrl-Dsends EOF —readreturns nonzero; break or exit- Trap
SIGINTif you need to clean up onCtrl-C
trap 'echo; echo "exiting"; exit' INT
When Not to Use select
- For complex forms with many fields — use
dialog/whiptailor a small curses UI - When choices contain spaces and you need exact matching —
selectworks, but it’s clunky
Next → getopts Option Parsing