Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

printf Command Guide

printf formats and prints text under your exact control. Unlike echo, it’s guaranteed by POSIX, supports format specifiers (%s, %d, %f), field widths, and padding — and it never interprets your data as flags or escapes. When output has to be precise, printf is the tool.

What is printf, and Why Use It?

You need:

  • columns that line up,
  • numbers zero-padded to a fixed width,
  • a value printed without a trailing newline,
  • output that’s identical on every POSIX shell.

echo can’t promise any of those. printf can:

printf '%-10s %5d\n' "web-01" 42
# web-01       42

printf '%03d\n' 7
# 007

printf 'No newline at end: %s' "done"

Format Specifiers

A printf format string is plain text punctuated by specifiers that start with %:

SpecifierPrints
%sA string
%d or %iA signed integer
%fA floating-point number
%x / %XHexadecimal (lower/upper case)
%cA single character
%%A literal percent sign

Each specifier consumes one argument, left to right:

printf '%s is %d years old\n' "wiki" 3
# wiki is 3 years old

printf '%d%% of disk used\n' 87
# 87% of disk used

Widths, Padding, and Alignment

Put a width (and optionally a - for left alignment) between % and the specifier:

printf '%10s|%s\n' "right" "aligned"
#     right|aligned

printf '%-10s|%s\n' "left" "aligned"
# left      |aligned

printf '%05d\n' 42
# 00042

printf '%8.2f\n' 3.14159
#     3.14

This is how you build aligned reports without reaching for awk:

printf '%-20s %s\n' "Package" "Status"
printf '%-20s %s\n' "nginx" "running"
printf '%-20s %s\n' "postgresql" "running"

printf and Newlines

printf does not add a trailing newline for you — the classic printf surprise:

printf 'a' 'b' 'c'
# abc        ← all on one line, no newline anywhere

printf '%s\n' 'a' 'b' 'c'
# a
# b
# c

The idiomatic fix — and the safe way to print any list — is to repeat the specifier with \n:

printf '%s\n' "${files[@]}"     # one array element per line

Reading and Printing: the while-read Loop

printf’s favorite habitat is inside loops that process input line by line:

# Safely transform every line of a file
while IFS= read -r line; do
  printf '%s\n' "$line"
done < server-list.txt

# With a counter
n=0
while IFS= read -r line; do
  n=$((n + 1))
  printf '%3d: %s\n' "$n" "$line"
done < server-list.txt

Compare this to while read ... do echo ... — printf wins whenever the line might start with - or contain backslashes, because echo would misread them.

printf in Scripts and Pipelines

# Generate arguments for another command
find . -name '*.log' -print0 | xargs -0 printf 'archiving %s\n'

# Write a precise line to a file
printf 'server.port=%d\n' 8080 > app.conf

# Timestamped log line with padding
printf '%(%Y-%m-%d %H:%M:%S)T [%s] %s\n' -1 "INFO" "started"

(The last line uses bash’s %(fmt)T extension for inline timestamps; in pure POSIX, combine printf with date: printf '%s %s\n' "$(date '+%F %T')" "message".)

Common Pitfalls

  • No automatic newline. Forget \n and your shell prompt collides with the output. Make \n a deliberate part of every format string.
  • Format string from untrusted input. printf "$user_input" executes whatever specifiers the input contains — including %s that swallow your arguments. Always keep the format literal: printf '%s' "$user_input".
  • Argument count mismatches. Too few arguments and printf reuses the format string (often printing it repeatedly); too many and the extras are printed with the last specifier. Count your specifiers.
  • printf doesn’t do arithmetic. printf '%d\n' "2+2" prints 2. Compute first: printf '%d\n' "$((2 + 2))", or use awk for math.
  • Locale decimals. %f may print 3,14 instead of 3.14 in some locales. Set LC_ALL=C when output must be machine-parseable.
  • echo — the simpler printer, and when it’s enough
  • awk — formatting plus real computation
  • redirection — sending formatted output to files
  • scripting — printf inside loops and scripts
  • date — timestamps to embed in formatted output

Cheatsheet

CommandWhat it does
printf '%s\n' "text"Print text with a newline
printf '%-10s|%5d\n' a 1Left/right aligned columns
printf '%03d\n' 7Zero-padded number → 007
printf '%8.2f\n' 3.14159Fixed-width float → 3.14
printf '%s\n' "${arr[@]}"Array elements, one per line
printf '%s' "$x"Safe print of any value
printf '%%\n'Print a literal percent sign