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

← All Bash builtins · Linux commands