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
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
fiselect: 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
doneselect 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.
