Printing formatted output with printf
Quick answer
Use printf when you need predictable terminal output or a report. A format string tells the command how to print each value. Keep the format fixed and pass variable text as a separate argument.
Prepare the practice environment
Use the chapter fixture described in lab-fixtures/text-streams/README.md. Run setup as a normal user in a disposable Linux environment, enter the printed directory and check pwd. Every example assumes a fresh fixture. Commands omit the terminal prompt; outputs below are not commands.
How it works
In printf FORMAT ARGUMENTS, %s prints a string, %d prints an integer, and \n in the format creates a newline. A width such as %-10s left-aligns a string in a minimum-width field; it does not truncate longer text. Bash normally provides printf as a builtin; GNU also supplies an external command. echo is convenient for fixed simple strings but handling of flags and backslashes varies across shells and implementations. A format is interpreted, so use printf '%s\n' "$value" for text rather than treating text as the format. Assignment name=value and expansion "$name" are briefly introduced here; the Bash track covers them in depth.
Read the format from left to right: literal characters appear as written, while each %s or %d conversion consumes a corresponding argument. A minimum width pads a short value; it is not a maximum length. With a fixed %s format, a percent sign in an argument is printed as data rather than interpreted as another conversion.
Try the examples
printf '%s: %d\n' 'Items' 3printf '%s: %s\n' 'State' 'ready'The format supplies separators and line endings; values fill placeholders in order.
Expected stdout:
Items: 3State: readyThe percent in the value is data, not a conversion instruction.
Expected stdout:
100% readyThe format repeats for the second pair; numbers are right-aligned.
Expected stdout:
open 2closed 12Common mistakes
Never use an arbitrary string as the printf format; percent signs and escapes can change output or cause errors. Do not rely on echo -e for portable formatting. printf does not automatically add LF unless requested.
Practice
Print Name: Mina and Count: 7 on separate lines using printf. Then print the literal string 50% without changing the format.
Related references
Study: printf, echo. These are reference names, not deployed links.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Printing formatted output — Knowledge Check
Apply the lesson concepts to the controlled text fixture.
Which format safely prints an arbitrary string followed by LF?
What does %d format?
What does %-8s specify?
Why prefer printf to echo -e for formatting?