Linux Basic — read with Prompts

1 minute read

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 PROMPT show a prompt (Bash builtin)
  • -r raw mode — don’t treat backslashes specially
  • -s silent — don’t echo input (useful for passwords)
  • -t SECONDS timeout
  • -n N read 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 -rsp for secrets and then echo a 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

Updated: