io
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.
printf FORMAT [ARG ...] Common flags / operators
| Flag / Operator | Purpose |
|---|---|
| %s | String conversion |
| %d / %i | Signed decimal integer |
| %q | Quote arg so it can be safely reused as shell input |
| -v VAR | Write result into variable VAR instead of stdout |
Examples
printf '%s\n' "$file" Safely prints any string (including -n) with a newline.
printf '%-10s %5d\n' name count Left-justify name in 10 cols, right-justify count in 5.
printf -v ts '%(%Y-%m-%d)T' -1 Bash 4.2+: assigns current date to $ts without a subshell.
printf '%s\n' "${arr[@]}" Format is reused per arg — one array element per line.
Gotcha
Backslash escapes in the format are always interpreted; use %s to print user-controlled strings so their contents aren't reinterpreted. %d with a non-numeric argument prints 0 with a warning to stderr.
Related
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.
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.
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.
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.
source (.)
Executes FILE in the CURRENT shell (no subshell), so variables, functions, and aliases defined in it persist. Contrast with 'bash file' which runs in a child process — its side effects vanish when it exits.