Introduction
The printf command is an essential tool in the Linux command line that allows formatting and displaying text in a controlled manner. Unlike echo, printf interprets escape sequences and accepts format specifiers similar to those in the C language, making it ideal for generating structured output in scripts and automations.
Basic Syntax
The general form of printf is:
printf FORMAT [ARGUMENTS...]
Where FORMAT is a string that may contain literal text and format specifiers, and ARGUMENTS are the values that will be substituted into those specifiers. If more arguments are provided than specifiers, the format is reused until all are consumed.
Most Common Format Specifiers
%s– text string.%dor%i– signed decimal integer.%f– floating‑point number.%xor%X– integer in hexadecimal (lowercase/uppercase).%o– integer in octal.%%– prints a literal percent sign.
These specifiers can be accompanied by modifiers that control width, precision, and alignment.
Simple Examples
Display a greeting:
printf "Hello, %s\n" "World"Output:
Hello, WorldDisplay several numbers:
printf "%d %d %d\n" 10 20 30Output:
10 20 30Width and Precision
A minimum width can be specified with a number between the
%and the specifier. For example,%5dreserves at least 5 characters, right‑aligned by default. To left‑align, use the minus sign:%-5s.Precision for floating‑point numbers is indicated by a dot followed by the number of decimal places:
%.2fshows two decimals.
printf "Value: %8.2f\n" 123.456Output:
Value: 123.46Escape Sequences
Just like in C,
printfinterprets sequences such as:
\n– newline.\t– horizontal tab.\r– carriage return.\\– literal backslash.\"– literal double quote.
These sequences allow creating more complex layouts without needing multiple calls.
Differences from echo
Although echo is simpler for printing plain text, its behavior regarding the -e and -n options varies across shells. printf is more portable and predictable because it always interprets escape sequences and does not automatically append a newline at the end (unless \n is included in the format). This makes it preferable in scripts where precise control of output is required.
Best Practices
- Use single quotes around the format when variable expansion is not needed, to avoid surprises.
- Prefer
%sfor strings and validate that arguments match the specifiers to avoid format errors. - In loops, reuse the same format to maintain consistency and improve readability.
- When printing only plain text without formatting, consider
printf '%s\n' "text"to avoid unexpected interpretation of escape sequences.
Conclusion
Mastering printf enables generating formatted, aligned, and numerically precise output in any Linux environment. Its syntax, inherited from C, provides flexibility that surpasses echo in most professional use cases, from simple messages to the creation of tables and automated reports.
This post is also available in ESPAÑOL.