printf Command Cheat Sheet
printf formats and prints data. It is far more robust and portable than echo, especially for scripting.
Synopsis
printf FORMAT [ARGUMENT]...
Basic Usage
Unlike echo, printf does not automatically add a newline (\n). You must add it manually.
printf "Hello World\n"
format Strings
%s: String%d: Integer%f: Float
printf "User: %s, ID: %d\n" "alice" 1001
# Output: User: alice, ID: 1001
Formatting Numbers
Precision (Floats)
Limit decimal places.
printf "Pi is approx %.2f\n" 3.14159
# Output: Pi is approx 3.14
Padding (Width)
Right-align numbers in a column of width 5.
printf "%5d\n" 10
printf "%5d\n" 200
# Output:
# 10
# 200
Leading Zeros
printf "%04d\n" 5
# Output: 0005
Formatting Columns (Tables)
Use negative width (%-10s) for left alignment.
printf "%-10s %-10s %s\n" "Name" "Role" "ID"
printf "%-10s %-10s %d\n" "Alice" "Admin" 101
printf "%-10s %-10s %d\n" "Bob" "User" 102
Name Role ID
Alice Admin 101
Bob User 102
Special Characters
\n: Newline\t: Tab\\: Backslash\b: Backspace
printf "Column1\tColumn2\n"
Assign to Variable
Using command substitution.
MSG=$(printf "Error: File %s not found" "config.txt")
echo "$MSG"
Notes
- Portability:
printfbehaves consistently across different shells (bash, zsh, dash), whereasechoflags (like-eor-n) vary significantly. Always preferprintffor scripts. - Arguments: If you provide more arguments than format specifiers,
printfreuses the format string.printf "%s\n" A B C # Output: # A # B # C