$linuxjunkies
>

printf(1)

Format and print text using a template string with variable substitution.

UbuntuDebianFedoraArch

Synopsis

printf FORMAT [ARGUMENT]...

Description

printf outputs text based on a format string, substituting placeholders with provided arguments. Unlike echo, it does not add a trailing newline by default and offers precise control over formatting through format specifiers.

Format specifiers begin with % and include type indicators like d (integer), s (string), f (float), and x (hexadecimal). Backslash escapes like \n (newline) and \t (tab) are interpreted in the format string.

If fewer arguments are provided than format specifiers, missing numeric values default to 0 and missing strings default to empty. Extra arguments are ignored.

Common options

FlagWhat it does
-v varnameAssign formatted output to shell variable instead of printing (bash extension)

Examples

Print a formatted string with a variable substitution and explicit newline

printf 'Hello, %s!\n' 'World'

Format integers with addition notation

printf '%d + %d = %d\n' 5 3 8

Left-align string in 10-char field, right-align number in 5-char field

printf '%-10s %5d\n' 'Item' 42

Convert decimal to hexadecimal (outputs: ff)

printf '%x\n' 255

Format floating-point number to 2 decimal places

printf '%.2f\n' 3.14159

Pad number with leading zeros to width 3 (outputs: 007)

printf '%03d\n' 7

Print ASCII characters using hex escape sequences (outputs: ABC)

printf '\x41\x42\x43\n'

Store formatted output in a variable instead of printing directly

printf -v result '%s_%s' 'foo' 'bar'; echo "$result"

Related commands