printf

The command that prints text according to a format string, such as printf '%s\n' "$name".

In more detail

%s stands for a string, %d for a whole number and %-12s for a string padded to 12 characters, and escape sequences such as \n work in the format. If there are more arguments than placeholders, the format repeats, which makes printf '[%s]\n' "$@" show each argument on its own line. It behaves the same in every shell, unlike echo.

Examples

printf '%-12s %5s\n' web01 443
printf 'third line\n' >> notes.txt
The format string says how to lay out the remaining arguments: %s inserts one argument as text and \n starts a new line. When there are more arguments than placeholders, printf repeats the format, which is why printf '%s\n' a b c prints three lines. It behaves the same on Linux and macOS, unlike echo, which makes it the portable choice for scripts.
printf '%s\n' NAME=Example VERSION=1 prints two lines, one per argument.

Related terms

Taught in

References