Script Valley
Bash Scripting for Developers
Control Flow and LogicLesson 2.5

Bash select menu and user input handling

select statement, read command, read -p prompt, read -s silent input, read -t timeout, PS3 variable, validating user input, reading from stdin vs arguments

Getting Input in Bash Scripts

Bash input sources

Scripts get input two ways: positional arguments ($1, $2) passed at invocation, or interactively via read at runtime. Know when to use each.

# Basic read
read -p "Enter your name: " username
echo "Hello, $username"

# Silent input (passwords)
read -sp "Password: " password
echo  # newline after silent input

# Timeout โ€” useful in automated scripts
read -t 10 -p "Continue? [y/N]: " answer || answer="N"

# Validate the input
if [[ ! "$answer" =~ ^[Yy]$ ]]; then
  echo "Aborted"
  exit 0
fi

select: Interactive Menus

#!/usr/bin/env bash
PS3="Choose an environment: "  # prompt for select

select env in production staging development quit; do
  case "$env" in
    production)
      echo "Deploying to prod..."
      break
      ;;
    quit)
      echo "Exiting"
      exit 0
      ;;
    *)
      echo "Invalid choice, try again"
      ;;
  esac
done

select automatically numbers options and loops until you break. PS3 sets the prompt string โ€” the default is #? which looks terrible, always override it.

For non-interactive scripts (cron jobs, CI pipelines), never use read โ€” use arguments or environment variables instead.

Bash select menu and user input handling โ€” Control Flow and Logic โ€” Bash Scripting for Developers โ€” Script Valley โ€” Script Valley