printf Explained: Why It Is Better Than echo

printf Explained: Why It Is Better Than echo

echo works until it does not. A string starting with a dash, a backslash in the middle, or a script moved to a different shell, and the behaviour changes. printf is the specified alternative and it does several things echo cannot.

Where echo goes wrong

echo "-n"
# prints nothing, because -n is taken as an option

echo "C:\new\table"
# bash builtin: C:\new\table
# sh on some systems: C:
#                     ew	able
# because \n and \t were interpreted

echo -e "a\tb"    # works in bash
echo -e "a\tb"    # prints "-e a\tb" in some shells

The root problem: echo is not consistently specified. POSIX leaves the behaviour of -n and backslash handling as implementation-defined, and shells differ. Bash’s builtin, dash’s builtin, and /bin/echo all behave differently.

# demonstrate it
bash -c 'echo -e "a\tb"'
dash -c 'echo -e "a\tb"'
/bin/echo -e "a\tb"

For a script you control, running under a shebang you control, echo is fine for plain strings. For anything portable, anything with escapes, or anything printing a variable whose contents you do not know, use printf.

printf -- '-n\n'
printf '%s\n' 'C:\new\table'
printf 'a\tb\n'

printf '%s\n' "$var" is the safe idiom for printing a variable, regardless of what it contains.

The basics

printf 'hello\n'
printf '%s\n' 'hello'
printf '%s and %s\n' 'this' 'that'

No automatic newline. You write \n. That is more typing and it means the output is exactly what you asked for, which matters when building output for another program.

The specifiers worth knowing:

SpecifierPrints
%sString
%dInteger
%iInteger, same as %d
%fFloat
%eScientific notation
%x %XHexadecimal, lower and upper
%oOctal
%cSingle character
%bString, interpreting escapes in the argument
%qShell-quoted, so it can be reused as input
%%A literal percent sign
printf '%d%%\n' 75
# 75%

Double the percent. A single % followed by something unrecognised is undefined and differs between implementations.

Width, alignment and precision

What makes printf worth using beyond safety.

printf '%-20s %10s\n' 'Name' 'Size'
printf '%-20s %10s\n' '--------------------' '----------'
printf '%-20s %10d\n' 'file1.txt' 1024
printf '%-20s %10d\n' 'a-longer-name.txt' 2048576
Name                       Size
-------------------- ----------
file1.txt                  1024
a-longer-name.txt       2048576
  • %-20s left-aligned in 20 columns
  • %10s right-aligned in 10
  • %.2f two decimal places
  • %05d zero-padded to 5 digits
  • %*s width taken from the next argument
printf '%.2f\n' 3.14159
# 3.14

printf '%05d\n' 42
# 00042

width=15
printf '%*s|\n' "$width" 'right'
printf '%-*s|\n' "$width" 'left'
# a table from real data
printf '%-25s %8s %12s\n' 'SERVICE' 'STATE' 'MEMORY'
systemctl list-units --type=service --state=running --no-legend --plain \
  | awk '{print $1}' | head -5 | while read -r unit; do
    mem=$(systemctl show -p MemoryCurrent --value "$unit")
    printf '%-25s %8s %12s\n' "${unit:0:25}" 'running' "$mem"
done

Our column guide covers the alternative when you want automatic width calculation rather than fixed columns.

Format reuse

The behaviour that surprises people, and the most useful one.

printf '%s\n' one two three
# one
# two
# three

The format string is reused until the arguments are exhausted. One specifier, three arguments, three lines.

# which makes this the idiomatic way to print an array
files=(a.txt b.txt c.txt)
printf '%s\n' "${files[@]}"

# or with two specifiers
printf '%s=%s\n' name alice role admin shell bash
# name=alice
# role=admin
# shell=bash
# and it composes with other tools
printf '%s\n' "${files[@]}" | sort
printf '%s\0' "${files[@]}" | xargs -0 ls -l

printf '%s\0' for null-separated output is the safe way to hand filenames to xargs, because it survives spaces and newlines in names. Our arrays guide covers the expansion.

-v, avoiding a subshell

# the usual way, which forks a subshell
formatted=$(printf '%-20s %s' "$name" "$value")

# no subshell
printf -v formatted '%-20s %s' "$name" "$value"
echo "$formatted"

Two advantages. It is faster, which matters in a loop. And it preserves trailing newlines, which command substitution strips:

x=$(printf 'a\n\n\n')
printf '%q\n' "$x"      # 'a', newlines gone

printf -v y 'a\n\n\n'
printf '%q\n' "$y"      # $'a\n\n\n', preserved

-v is a bash builtin feature and not available in /usr/bin/printf.

%q, for safe reuse

file='my file with spaces.txt'
printf '%q\n' "$file"
# my\ file\ with\ spaces.txt

# which means you can generate commands safely
printf 'rm -- %q\n' "$file"
# rm -- my\ file\ with\ spaces.txt

Useful for logging a command as it could be re-run, and for generating scripts. Our quoting guide covers why this is harder than it looks.

The time format

Bash-specific and genuinely useful.

printf '%(%Y-%m-%d)T\n' -1
printf '%(%F %T)T\n' -1
printf '%(%F)T\n' 1795000327

-1 means now, and a number is treated as epoch seconds. This avoids forking date, which is roughly two orders of magnitude faster in a loop.

Practical uses

# a progress line that overwrites itself
for i in {1..100}; do
    printf '\rprogress: %3d%%' "$i"
    sleep 0.02
done
printf '\n'
# human-readable sizes without numfmt
bytes=1536000
printf '%.1f MB\n' "$(bc -l <<< "$bytes / 1048576")"

# or let numfmt do it
printf '%s\n' "$bytes" | numfmt --to=iec
# generating config files
cat > /etc/myapp.conf <<EOF
$(printf 'listen = %s:%d\n' "$host" "$port")
$(printf 'workers = %d\n' "$workers")
EOF

# or directly
printf 'listen = %s:%d\nworkers = %d\n' "$host" "$port" "$workers" \
  | sudo tee /etc/myapp.conf
# colour output, where the escape needs printf
printf '\033[1;31merror:\033[0m %s\n' 'something broke'

# better, using tput so it degrades on a dumb terminal
red=$(tput setaf 1); bold=$(tput bold); reset=$(tput sgr0)
printf '%s%serror:%s %s\n' "$bold" "$red" "$reset" 'something broke'

tput reads terminfo, so it produces nothing when output is not a terminal, which is what you want when the output is being piped to a file. Our terminal emulators post covers terminfo and why TERM matters.

Errors to expect

printf '%d\n' abc
# bash: printf: abc: invalid number
# prints 0 and returns non-zero

A non-numeric argument to %d is an error, which is useful: it catches bad input rather than printing something wrong. Check the exit status if it matters, per our exit codes guide.

printf '%s %s\n' one
# one
# with the second specifier producing nothing

Missing arguments produce empty output rather than an error. No warning, so a format string with more specifiers than arguments silently prints less than you expected.

# never do this
printf "$user_input"
# a % in the input is a format specifier

# always
printf '%s' "$user_input"

Never put untrusted data in the format string. A %s in the input consumes an argument that does not exist, and %n historically was a security problem in C. In shell it is a correctness bug rather than a vulnerability, and it is still wrong.

Frequently Asked Questions

Why use printf instead of echo?

echo behaviour varies between shells and builds, particularly for backslash escapes and the -n and -e options, so a script using it is not reliably portable. printf has defined behaviour, handles format specifiers, and does not interpret its arguments as options in the same way.

Does printf add a newline like echo does?

No, which is the main difference people notice first. You include a newline in the format string explicitly with a backslash n. That is more typing and it means the output is exactly what you specified rather than what the shell decided.

What happens if I give printf more arguments than format specifiers?

The format string is reused until the arguments run out, which is a feature rather than an error. It means a format with one specifier and twenty arguments produces twenty lines, and that is the idiomatic way to format a list.

How do I print a literal percent sign with printf?

Double it, so two percent signs produce one in the output. A single percent followed by an unrecognised character is undefined behaviour and varies between implementations, so doubling is the only reliable approach.

Should I use the printf builtin or /usr/bin/printf?

The builtin, which is what you get by default in bash and is faster because no process is started. The external binary exists for shells without a builtin and for the -v option it lacks. Behaviour differs slightly between them for some edge cases.

How do I store printf output in a variable without a subshell?

Use the -v option, which writes to a named variable directly. That avoids the command substitution subshell, which is faster in a loop and preserves trailing newlines that command substitution would strip.