Reading User Input with read
The read builtin reads a line from stdin into variables. Learn prompts, silent input for passwords, timeouts, and reading into arrays.
January 19, 20266 min read
BashInputreadScripting
Interactive scripts need to accept user input. Bash's read builtin reads a line from standard input and stores words into variables. It has flags for prompts, silent mode (passwords), timeouts, and reading into arrays.
Basic read
# Read into one variable
read name
echo "Hello, $name"
# Multiple variables — splits on IFS (space by default)
read first last
# user types: Alice Smith
echo "First: $first, Last: $last" # First: Alice, Last: Smith
# Extra words go into the last variable
read a b rest
# user types: one two three four five
echo "a=$a, b=$b, rest=$rest" # a=one, b=two, rest=three four fiveUseful read Flags
read flags reference
| Flag | Purpose |
|---|---|
-p "prompt" | Print prompt before reading (no newline) |
-s | Silent mode — don't echo input (passwords) |
-t N | Timeout after N seconds; returns exit code 1 |
-n N | Read exactly N characters (don't wait for Enter) |
-r | Raw mode — backslashes are NOT escape characters |
-a arr | Read words into indexed array |
-d char | Use char as delimiter instead of newline |
-e | Use readline (allows arrow keys, history) |
# Prompted input (always use -r)
read -rp "Enter your name: " name
echo "Hello, $name"
# Password (silent)
read -rsp "Enter password: " password
echo "" # newline after silent input
echo "Password length: ${#password}"
# Timeout — useful in automation
if read -rt 10 -p "Confirm? [y/N] " response; then
echo "Got response: $response"
else
echo ""
echo "Timed out — using default"
response="n"
fi
# Read a single keypress (no Enter needed)
read -rn 1 -p "Press any key to continue..."
echo ""
# Read into array
read -ra colors -p "Enter colors (space-separated): "
echo "You entered ${#colors[@]} colors"
for c in "${colors[@]}"; do echo " - $c"; doneConfirmation Prompt Pattern
function confirm {
local prompt="${1:-Are you sure?} [y/N] "
local response
read -rp "$prompt" response
case "${response,,}" in # lowercase the response
y|yes) return 0 ;;
*) return 1 ;;
esac
}
if confirm "Delete all files?"; then
echo "Deleting..."
else
echo "Cancelled"
fiReading from a Here-String
# read can also consume strings directly
read -r first second <<< "hello world"
echo "$first" # hello
echo "$second" # world
# Useful for parsing output
IFS=: read -r user _ uid gid _ home shell <<< "alice:x:1000:1000::/home/alice:/bin/bash"
echo "User: $user, UID: $uid, Shell: $shell"Quick Check
What does `read -s -p "Password: " pw` do?
Exercise
Write a function ask_yes_no that:
- Takes a question string as argument
- Reads a response with a 30-second timeout
- Returns 0 if user types "y" or "yes" (case-insensitive)
- Returns 1 for "n", "no", or timeout
- If the answer is invalid, ask again (use a loop)