Linux Basic — select Statement

less than 1 minute read

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
  • $opt gets the chosen word (or empty if invalid)
  • $REPLY is the numeric choice
  • PS3 sets 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-D sends EOF — read returns nonzero; break or exit
  • Trap SIGINT if you need to clean up on Ctrl-C
trap 'echo; echo "exiting"; exit' INT

When Not to Use select

  • For complex forms with many fields — use dialog/whiptail or a small curses UI
  • When choices contain spaces and you need exact matching — select works, but it’s clunky

Next → getopts Option Parsing

Updated: