When to use printf
Use printf for predictable text formatting in shell commands and scripts. Keep the format string constant and pass variable data as arguments so percent characters in input are not treated as formatting instructions.
Syntax
printf FORMAT [ARGUMENTS...]Square brackets mark optional arguments; an ellipsis means repetition. Replace example file names, user names and server addresses with your own values.
Common options and arguments
Usage examples
Safely output text
printf '%s\n' 'Hello, server'A single string is printed with a terminating newline.
Form two columns
printf '%-12s %s\n' 'service' 'status'A fixed-width label and value produce a simple aligned row.
Output variable as data
printf '%s\n' "$HOME"The home-directory value is printed as data through a constant format string.
Notes and limitations
- Keep the format constant and pass user data as separate arguments.
- An embedded version is available in Bash; additional specifiers may differ from external printf.
Common questions and troubleshooting
Why not use variable content as the format string?
Percent sequences can be interpreted as directives. Use a literal format and supply untrusted or variable text through string arguments.
Does printf always add a newline?
No. Include the newline escape in the format when needed; otherwise later output can continue on the same terminal line.
Further help
Options vary by version and distribution. Check the installed documentation with this command: man printf.