← All commands
THE COMMAND REFERENCE

printf

Print text using a format string, with exact control over newlines and escapes.

Last updated

Portable / common

Implementation-level reference; examples are not certified for every installed version.

Overview

printf prints text built from a format string and arguments, as the C function of the same name does. Unlike echo, it does not add a newline, understands backslash escapes the same way everywhere, and can pad, round and convert numbers. When the arguments outnumber the format, the format is used again, which makes a one-line list into many lines.

Background

The printf command takes its format language from the C library function. Today the name covers the Bash builtin, GNU printf, the printf that macOS ships, and the printf applet in BusyBox. They agree on %s, %d, %f, %b and the usual backslash escapes.

Examples

Print two values with a format; \n ends the line:

printf '%s-%s\n' a b

Round a number to two decimals, padded to five characters:

printf '%5.2f|\n' 3.14159

Convert a hexadecimal number to decimal:

printf '%d\n' 0x1f

Reuse the format for every extra argument, one line each:

printf '%s\n' a b c

Print a tab and a newline from escapes:

printf 'a\tb\n'

Expand escapes inside an argument with %b:

printf '%b' 'a\tb\n'

Common mistakes

Never put untrusted text in the format position: printf "$text" treats % and backslashes in it as instructions. Use printf "%s\n" "$text" instead. The format needs \n for a newline; nothing is added for you. With no arguments %s prints nothing and %d prints 0, which can hide a missing variable. Floating-point results can differ in the last digits between implementations.

Portability

Only %s, %d with a hexadecimal argument, %5.2f, %b and the tab and newline escapes are in the Common examples. %q for shell quoting and -v to store the result in a variable are Bash builtin features, not in the executables. In a plain sh script the builtin may behave differently from both Bash and the executable; the macOS /bin/sh, for example, printed -n as text for echo -n in the check. The Common examples were executed on Bash 5.2, GNU coreutils 9.11, macOS system tools, and BusyBox 1.37.0 (see the development guide for the exact check).

References

Original explanations, with upstream documentation for further reading. FreeBSD references are comparison material, not a claim of Apple version equivalence.