io
read
Reads a single line from stdin (or a file descriptor) and splits it into the given variables using IFS. The workhorse for line-by-line input processing and interactive prompts.
read [-r] [-p PROMPT] [-a ARRAY] [-t TIMEOUT] [-d DELIM] [VAR ...] Common flags / operators
| Flag / Operator | Purpose |
|---|---|
| -r | Raw mode — don't interpret backslashes (always use this) |
| -p PROMPT | Print PROMPT before reading |
| -a ARRAY | Split words into indexed array ARRAY |
| -t SECONDS | Timeout after N seconds (fractional allowed) |
| -s | Silent — don't echo input (passwords) |
| -n N | Return after N characters instead of a full line |
Examples
read -rp 'Name: ' name Prompt and read one line into $name.
while IFS=: read -r user _ uid _; do echo "$user $uid"; done < /etc/passwd Split /etc/passwd on colons per line.
read -rsp 'Password: ' pw; echo Silent password prompt; trailing echo adds a newline.
read -ra parts <<< "$line" Here-string splits $line into an array using IFS.
Gotcha
Without -r, backslashes are treated as line-continuation and escape processing — almost always wrong. IFS is applied on the read, so 'IFS= read -r line' preserves leading/trailing whitespace.
Related
while / until / do / done
Repeats the body while (or until) the condition command exits 0. 'while' loops while the condition succeeds; 'until' is the inverse and is idiomatic for polling until a service becomes ready.
printf
Formats and prints arguments according to a C-style format string. Portable, precise, and reuses the format string if extra arguments are provided — the preferred replacement for echo when you need formatting.
declare / typeset / readonly
Declares variables with attributes: arrays, associative arrays, integers, readonly, lowercase/uppercase, exported. 'readonly' is a shortcut for 'declare -r' that locks a variable so it cannot be reassigned or unset for the lifetime of the shell.
echo
Writes arguments to stdout separated by spaces and terminated with a newline. Behavior across systems is inconsistent (especially escape processing) — prefer printf for anything with formatting or portability requirements.
exec
Replaces the current shell process with COMMAND (no new process is created). Without a command, applies redirections permanently to the current shell — a common way to open long-lived file descriptors.