Skip to main content

printf Cheatsheet

By Dejan Panovski •Updated on • Download PDF

printf reference for Bash: format specifiers, flags, width and precision, escape sequences, %(fmt)T dates, padded columns, and common errors.

The printf command prints text through a format string. Specifiers such as %s and %d mark where each argument goes and how it looks. The examples use the Bash builtin, the version that runs when you type printf in Bash. /usr/bin/printf, dash, and awk differ in a few places, listed in their own card.

Basic Syntax

The format is reused until every argument is consumed.

CommandDescription
printf FORMAT [ARGUMENTS...]Print the arguments formatted by FORMAT
printf '%s\n' "$var"Print a variable followed by a newline
printf 'Done\n'A format alone; printf never adds a newline itself
printf '%s\n' one two threeFormat reused for each argument; prints three lines
printf '%s=%s\n' a 1 b 2Reused two arguments at a time; prints a=1 and b=2
printf '%s %d\n' xMissing arguments print as an empty string or 0
printf -v var '%05d' 42Store 00042 in var instead of printing it
printf -- '-n\n'-- ends options; needed when the format starts with -
printf '%s\n' "$msg" >&2Print to standard error

Format Specifiers

Each specifier takes one argument, except %%.

SpecifierDescription
%sString
%bString with backslash escapes expanded
%qString quoted for reuse as shell input
%cFirst character of the argument
%d, %iSigned decimal integer
%uUnsigned decimal integer; -1 prints 18446744073709551615
%oOctal integer; 8 prints 10
%x, %XHexadecimal in lowercase or uppercase; 255 prints ff or FF
%fDecimal number, six places by default; 3.14159 prints 3.141590
%e, %EExponential notation; 12345.678 prints 1.234568e+04
%g, %G%f or %e style, depending on the exponent; 1234567 prints 1.23457e+06
%a, %AHexadecimal floating point; 1 prints 0x1p+0
%(fmt)TDate and time from epoch seconds
%%Literal % sign

Flags

Flags go right after %, before the width.

FormatDescription
%-8sLeft-align in the field; abc prints abc
%08.3fPad with zeros; 3.14159 prints 0003.142
%+dAlways show the sign; 5 prints +5
% dSpace before positive numbers, - before negative ones
%#x, %#oAdd the 0x or 0 prefix; 255 prints 0xff
%#gKeep trailing zeros; 1.5 prints 1.50000
%'dGroup digits by locale; 1,234,567 with en_US.UTF-8, 1234567 with C
%-05d- wins over 0; pads with spaces on the right

Width and Precision

The full form is %[flags][width][.precision]specifier. Width is a minimum; precision depends on the type.

FormatDescription
%10sRight-align in 10 columns
%-10sLeft-align in 10 columns
%.3sCut the string to 3 characters; abcdef prints abc
%10.3sCut to 3 characters, then right-align in 10 columns
%.2fTwo decimal places; 3.14159 prints 3.14
%.5dAt least 5 digits; 42 prints 00042
%05dZero-pad to 5 columns; -42 prints -0042
printf '%*s' 10 abcWidth taken from the argument before the value
printf '%.*f' 2 3.14159Precision taken from an argument; prints 3.14
printf '%*.*f' 10 2 3.14159Width and precision both from arguments
printf '%*s' -10 abcA negative * width left-aligns

Escape Sequences

Escapes work in the format string and in %b arguments. %s prints them as typed.

EscapeDescription
\nNewline
\tHorizontal tab
\\Backslash
\rCarriage return; moves the cursor to the start of the line
\aAlert (terminal bell)
\bBackspace
\v, \fVertical tab, form feed
\eEscape character for ANSI codes: printf '\e[1mbold\e[0m\n'
\NNNByte with octal value NNN; \101 prints A
\xHHByte with hex value HH; \x41 prints A
\uHHHH, \UHHHHHHHHUnicode character; \u00e9 prints é
printf '%b\n' 'one\ctwo'\c in a %b argument stops all output; prints one

Numbers and Bases

Convert between bases and character codes without bc.

CommandDescription
printf '%d\n' 0xffHex to decimal; prints 255
printf '%x\n' 255Decimal to hex; prints ff
printf '%o\n' 493Decimal to octal; prints 755
printf '%d\n' 010A leading 0 means octal; prints 8
printf '%d\n' "'A"Character code; prints 65
printf "\\x$(printf %x 65)\n"Code to character; prints A
printf '%02x' 10 255 0Two-digit hex bytes; prints 0aff00
printf '%d.%d.%d.%d\n' 0xC0 0xA8 1 1Hex octets to an IP address; prints 192.168.1.1
printf '%.0f %.0f\n' 2.5 3.5Halves round to the even number; prints 2 4
printf '%5.1f%%\n' 99.5Percentage with a literal % sign

Text Recipes

Common one-liners for repeated characters, arrays, and files.

CommandDescription
printf '%.0s-' {1..20}; echoPrint - 20 times
printf -v line '%*s' 40 ''; echo "${line// /=}"Build a line of 40 = signs
printf '%s\n' "${arr[@]}"Print each array element on its own line
printf -v csv '%s,' "${arr[@]}"; echo "${csv%,}"Join array elements with commas
printf 'file-%03d.txt\n' 1 2 10Zero-padded names; file-001.txt to file-010.txt
printf '%s\n' banana apple | sortSend lines to another command
printf 'line1\nline2\n' > notes.txtWrite several lines to a file
printf '%s\n' "$entry" >> notes.txtAppend a line to a file

Tables and Columns

Use the same widths in the header and in the rows.

CommandDescription
printf '%-10s %8s\n' NAME SIZEHeader with a left-aligned name and a right-aligned size
printf '%-10s %8d\n' nginx 1024 mysql 20480Two rows from one call
printf '%-10s %6.2f\n' cpu 3.5 mem 42.123Fixed decimals keep numbers aligned
printf '%-*s %s\n' "$width" "$name" "$value"Column width from a variable
printf '%s\t%s\n' "$name" "$value"Tab-separated output for cut or awk
printf '%-10ls %s\n' "$name" "$value"Pad by characters, not bytes (Bash 5.3 and later)

Dates and Times

%(fmt)T is Bash only. fmt takes the same codes as date +FORMAT .

CommandDescription
printf '%(%F %T)T\n' -1Current date and time; -1 means now
printf '%(%F)T\n'No argument also means now
printf '%(%T)T\n' -2Time the shell started
printf '%(%F %T)T\n' 1700000000Format epoch seconds
TZ=Asia/Tokyo printf '%(%F %T)T\n' 0Another time zone; prints 1970-01-01 09:00:00
printf -v today '%(%F)T' -1Store the date without running date
printf '%(%s)T\n' -1Current epoch seconds
printf '[%(%T)T] %s\n' -1 "$msg"Timestamped log line

Shell Quoting

%q escapes a value so the shell reads it back unchanged.

CommandDescription
printf '%q\n' "$file"Quote a value for reuse as shell input
printf '%q\n' "it's a \$file"Prints it\'s\ a\ \$file
printf '%q\n' $'tab\tx'Control characters use $'...'; prints $'tab\tx'
printf '%q ' rm -f "my file.txt"Build a command string; prints rm -f my\ file.txt
ssh server "ls -l $(printf '%q' "$dir")"Pass a path with spaces through ssh
printf '%#q\n' "a b"Single-quote style; prints 'a b' (Bash 5.3 and later)
printf '%s\n' "${var@Q}"Same idea with parameter expansion

Replacing echo

printf prints values such as -n or -e as data. echo reads them as options.

printfecho equivalent
printf '%s\n' "$var"echo "$var"
printf '%s' "$var"echo -n "$var"
printf '%b\n' "$var"echo -e "$var"
printf '\n'echo (blank line)
printf '%s\n' "$a" "$b"Two echo commands

Other printf Versions

sudo, env, xargs, and find -exec run /usr/bin/printf. Scripts started with sh use the dash builtin on Ubuntu and Debian.

ItemDifference
type -a printfLists the builtin first, then /usr/bin/printf
-v varBash only; /usr/bin/printf prints -v as text and dash exits with an error
%(fmt)TBash only; other versions report an invalid conversion or directive
%q/usr/bin/printf prints 'a b' where Bash prints a\ b; dash has no %q
\xHH, \uHHHHdash prints them as typed
printf '-n\n'Bash reads -n as an option; /usr/bin/printf prints it
awk '{printf "%-8s %5d\n", $1, $2}' file.txtawk separates arguments with commas and does not reuse the format
awk 'BEGIN { printf "%c\n", 65 }'awk turns a number into a character (A); Bash %c prints 6

Common Mistakes

Quick checks for common printf errors and surprises.

ProblemFix
Output runs into the next promptEnd the format with \n
printf "$var" mangles % or \Pass data as an argument: printf '%s\n' "$var"; 50% off prints 500ff otherwise
printf: -n: invalid optionUse printf -- '-n\n' or printf '%s\n' -n
printf: 3.5: invalid number%d takes integers only; use %.0f or cut the decimals with ${n%.*}
printf: 08: invalid octal numberA leading zero means octal; force base 10 with $((10#08))
%s prints \t literallyUse %b for arguments that contain escapes
%c prints 6 for 65%c takes the first character; use printf "\\x$(printf %x 65)"
An empty array still prints a blank lineThe format runs once with no arguments; check ${#arr[@]} first
Accented text breaks alignment or gets cut%s width and precision count bytes; use %ls in Bash 5.3 and later
%.2f prints 2.67 for 2.675Expected: the binary value of 2.675 is slightly below it
Numerical result out of rangeIntegers stop at 9223372036854775807; use bc for larger values

Bash Version Support

Run echo "$BASH_VERSION" to check your version. macOS still ships Bash 3.2.

FeatureMinimum Bash
printf -v var3.1
printf -v 'arr[i]'4.1
%(fmt)T, \u, \U4.2
%(fmt)T with no argument4.3
%ls and %lc in characters, %#q5.3

Use these guides for worked examples and related syntax.

GuideDescription
Bash printf CommandFull printf guide with examples
echo Command in LinuxSimple output and its options
Bash CheatsheetVariables, conditionals, loops, and functions
Bash Parameter Expansion CheatsheetTrimming, replacement, and ${var@Q}
date CheatsheetFormat codes for %(fmt)T
awk Cheatsheetprintf inside awk programs