Linux printf Command: Print Values with a Defined Format
printf prints strings and numbers according to a format string. It is useful in shell scripts because it can control line breaks and column widths more precisely than echo.
What is the printf command?
In Bash, printf is a shell builtin, but an external printf from GNU Coreutils may also exist. You can check which implementation is used by running type printf. Since there is no automatic newline, include \n in the format string if needed.
Basic syntax
printf 'format string' [values...]
The installed implementation and options may vary depending on the distribution. Check the current system's documentation with man printf.
Examples
Strings and line breaks
Place values in %s and end the line with \n.
printf 'Hello, %s\n' Linux
Aligning column widths
Set left-alignment widths and number widths to create a simple table.
printf '%-12s %5d\n' apple 42
Repeating multiple values output
The format string is repeatedly applied to the remaining arguments.
printf '%s\n' one two three
Comparing Format Strings and Actual Output
printf inserts arguments into the format specifiers in order. %-6s displays a string left-aligned with a width of 6, and %03d fills an integer with zeros up to three digits.
printf '[%-6s] [%03d]\n' apple 7
Example output:
[apple ] [007]
The \n at the end of the format string is a line break. Unlike echo, printf does not guarantee automatic line breaks, so specify it if needed. If user input is placed directly in the format string, % or backslashes could be interpreted, so use a fixed format like printf '%s\n' "$value".
Main Options and Format
| Options/Format | Description |
|---|---|
%s |
Prints the value as a string. |
%d |
Prints an integer in decimal. |
%f |
Prints a floating-point number with the specified precision. |
\n |
Represents a line break within a format string. |
%-Ns |
Left-aligns a string within at least N spaces. |
Precautions when using
If user input is passed as the format string itself, % specifications are interpreted. To safely print the value, use a fixed format like printf '%s\n' "$value". Quote shell variables to prevent word splitting and wildcard expansion.
Frequently Asked Questions
Does printf automatically add a newline at the end like echo?
No. To change lines, you need to insert \n directly into the format string.
Official Documentation
You can check the exact behavior of the options and implementation differences in the official documentation for printf.
For the behavior of external commands, also refer to the official GNU Coreutils manual.









