Linux Basic — read with Prompts
read with Prompts
read is how scripts ask users for input. It is surprisingly flexible: prompts, timeouts, single-character reads, and secret input.
Common read Flags
-p PROMPTshow a prompt (Bash builtin)-rraw mode — don’t treat backslashes specially-ssilent — don’t echo input (useful for passwords)-t SECONDStimeout-n Nread N characters (no newline required)
read -rp "Username: " user
read -rsp "Password: " pass
echo
-r is recommended almost always to avoid surprises with backslashes.
Defaults and Timeouts
read -t 10 -rp "Continue? [y/N] " ans || ans="n"
# if timeout occurs, read exits nonzero, so we set default
When using timeouts, always provide a sensible default because read returns non-zero on timeout.
Single-Character Confirmation
read -n1 -rp "Press any key to continue..." key
echo
This is handy for one-off confirmations or stepping through a tour.
Slurp Lines: mapfile / readarray
mapfile -t lines < <(some_command)
echo "read ${#lines[@]} lines"
mapfile reads stdin into an array, one element per line — no subshell traps, and it’s fast.
Secure Input Practices
- Always
read -rspfor secrets and thenechoa newline after to keep the prompt neat. - Do not store secrets in world-readable files. If you must cache a secret, use a secure keyring.
Next → Input Validation Loops