← Full reference

echo and printf

Printing text from a script — echo and its traps, and printf with the %s %d %f %x %q %b formats

echo prints its arguments separated by spaces and adds a newline. That's handy for simple messages, but echo's behavior depends on options and the shell. printf prints strictly according to a format template — that's how you output tables, numbers with the right precision, strings without a newline and any data "as is". In bash both commands are builtins; their help is help echo and help printf.

Syntax

echo [-neE] [argument…]
printf [-v variable] format [argument…]

echo options

OptionWhat it does
-ndon't add a newline at the end
-einterpret escape sequences in the arguments (\n, \t, …)
-Edon't interpret escape sequences (the default in bash)

The builtin echo has no other options: it doesn't understand -- and prints it as text.

Escape sequences

They work in echo -e, in the printf format, in printf arguments for %b and inside $'…'.

NotationWhat it is
\n / \t / \rnewline / tab / carriage return
\\the backslash itself
\a / \b / \f / \vbell / backspace / form feed / vertical tab
\e (\033)the ESC character — start of terminal color codes: \e[31m red, \e[1m bold, \e[0m reset
\xHHa byte in hex: \x41 → A
\0NNN (echo, %b) / \NNN (printf format)a byte in octal: \0101 / \101 → A
\uHHHH / \UHHHHHHHHa Unicode character: \u00e9 → é
\ccut the output short: nothing after \c is printed, including the newline

printf specifiers

The format is a string of plain text and %… specifiers. Each specifier consumes the next argument.

SpecifierWhat it printsExample → result
%sthe string as isprintf '%s\n' 'a\tb' → a\tb
%bthe string, interpreting escape sequences in itprintf '%b\n' 'a\tb' → a<tab>b
%d, %ia signed integerprintf '%d' 0x1f → 31
%uan unsigned integerprintf '%u' -1 → 18446744073709551615
%fa decimal with 6 digits after the pointprintf '%f' 2.5 → 2.500000
%e / %gexponential notation / the shorter of %f and %eprintf '%e' 12345.678 → 1.234568e+04
%x / %Xhexadecimal, lower / upper caseprintf '%x' 255 → ff
%ooctalprintf '%o' 8 → 10
%cthe first character of the argumentprintf '%c' hello → h
%qthe string escaped for reuse as shell inputprintf '%q' "a b'c" → a\ b\'c
%(format)Ta date using a strftime template; the argument is Unix time, -1 — nowprintf '%(%F %T)T\n' -1
%%a literal percent signprintf '100%%' → 100%

Numeric arguments can be written as 0x1f (hex), 010 (octal = 8) and "'A" — the character code (printf '%d' "'A" → 65).

Width, precision, flags

General form of a specifier: %[flags][width][.precision]type.

NotationWhat it doesExample → result
%8swidth 8, right-aligned[%8s] with hi → [ hi]
%-8swidth 8, left-aligned[%-8s] with hi → [hi ]
%08dpad with zeros on the left%08d with 42 → 00000042
%+dalways show the sign%+d with 5 → +5
%.2f2 digits after the point (rounded)%.2f with 3.14159 → 3.14
%8.3fwidth 8 and 3 digits after the point[%8.3f] with 2.5 → [ 2.500]
%.3struncate the string to 3 bytes%.3s with abcdef → abc
%*d / %-*stake the width from an argumentprintf '%*d' 5 42 → 42
%#x / %#oadd a 0x / 0 prefix%#x with 255 → 0xff

Format reuse and -v

If there are more arguments than specifiers, printf cycles through the format until the arguments run out. Missing arguments count as an empty string (zero for numbers):

printf '%s\n' a b c          # three lines: a, b, c
printf '%s=%s\n' a 1 b 2 c   # a=1, b=2, c=

printf -v name format … doesn't print but stores the result in a variable — without a $(…) subshell:

printf -v id '%05d' 42       # id=00042

Examples

# a message without a newline, the cursor stays on the same line
echo -n "Wait… "; sleep 1; echo "done"

# each array element on its own line (more reliable than echo "${arr[@]}")
arr=("first file" second third)
printf '%s\n' "${arr[@]}"

# a neat table: name left-aligned in 10 characters, number right-aligned in 6
printf '%-10s %6s\n' NAME SIZE
printf '%-10s %6d\n' config 120 data.db 20480

# a number with two decimal places and with leading zeros
printf '%.2f\n' 3.14159        # 3.14
printf '%03d\n' 7              # 007

# convert a number to hex and back
printf '%x\n' 255              # ff
printf '%d\n' 0xff             # 255

# colored text: red, then reset
printf '\e[31m%s\e[0m\n' "ERROR"

# a string that can be safely inserted into a command
printf '%q\n' "file with spaces.txt"   # file\ with\ spaces.txt

# the current date without calling date
printf '%(%Y-%m-%d %H:%M)T\n' -1

# print to stderr
printf 'error: %s\n' "no such file" >&2

Pitfalls

  • echo doesn't understand --. echo -- -n prints -- -n. And if a variable happens to contain -n or -e, echo "$x" takes it as an option and prints nothing. For arbitrary data write printf '%s\n' "$x".
  • echo without -e doesn't expand \n. echo "a\tb" prints a literal a\tb. In other shells (e.g. sh → dash) echo always expands them — so use printf in portable scripts.
  • Don't put data into the format. printf "$var\n" breaks if $var contains % or \: the string discount 100% gives an invalid format character error and exit code 1. The right way is printf '%s\n' "$var".
  • printf doesn't add a newline itself. Without \n in the format, the next line of output sticks to this one.
  • %d is for integers only. printf '%d' 3.5 prints 3, writes invalid number to stderr and returns exit code 1. For decimals use %f / %.Nf.
  • %.0f rounds half to even: 0.5 → 0, 1.5 → 2, 2.5 → 2.
  • Width and precision count bytes, not characters. An accented letter like ä takes 2 bytes, so printf '[%6s]' äöü prints [äöü] with no padding, and %.2s of äöü gives a single letter. Align tables with non-ASCII text using column -t.
  • An empty array still produces a line. printf '%s\n' "${arr[@]}" with an empty arr prints one empty line: the format is applied at least once.

See also

read · redirection · variables · column · date