patternbashModerate
printf vs echo: portability and control over output formatting
Viewed 0 times
printfechoformattingportabilitynewlineescape sequencesoutput
Problem
'echo' behavior is inconsistent across systems. 'echo -e' interprets escapes on some systems and prints '-e' literally on others. 'echo -n' suppresses newlines on some but not all implementations.
Solution
Use 'printf' for any output where you care about exact formatting. Reserve 'echo' for simple, untransformed strings.
# BAD: inconsistent across systems
echo -e "Name:\tAlice"
echo -n "no newline"
# GOOD: printf is POSIX-defined and predictable
printf "Name:\tAlice\n"
printf '%s' "no newline"
printf '%d items\n' "$count"
printf '%s\n' "${array[@]}" # print each element on its own line
# BAD: inconsistent across systems
echo -e "Name:\tAlice"
echo -n "no newline"
# GOOD: printf is POSIX-defined and predictable
printf "Name:\tAlice\n"
printf '%s' "no newline"
printf '%d items\n' "$count"
printf '%s\n' "${array[@]}" # print each element on its own line
Why
POSIX specifies printf's behavior precisely. echo's behavior with -n and -e flags is explicitly left implementation-defined by POSIX, making it a portability hazard.
Gotchas
- printf repeats its format string if given more arguments than format specifiers: printf '%s\n' a b c prints three lines
- printf does not add a newline automatically — always include \n in the format
- printf '%s' is safe for printing arbitrary strings that may start with -
- echo -- is NOT portable (some implementations print --, others suppress it)
- In bash, echo handles most simple cases fine — only avoid it for escape sequences or -n
Code Snippets
printf usage patterns
# Portable formatting
printf 'Hello, %s! You have %d messages.\n' "$name" "$count"
# Print each array element on its own line
fruits=(apple banana cherry)
printf '%s\n' "${fruits[@]}"
# Right-align numbers in a column
for i in 1 10 100 1000; do
printf '%6d\n' "$i"
done
# Hex dump a value
printf '0x%08X\n' 255 # 0x000000FF
# Write to stderr
printf 'Error: %s\n' "$message" >&2Context
Generating formatted output in scripts that may run on different systems
Revisions (0)
No revisions yet.