Ad space (banner)
🖥️Linux Lessons
Lesson 60 / 61

Formatting Output with printf

printf is for when "I want to display a variable's value neatly, in a fixed format." printf lets you control the output format in much finer detail than echo, using format specifiers for strings, numbers, newlines, and more.

Use it in the form printf "format" value1 value2 .... %s is a string specifier, %d is an integer specifier, and \n represents a newline.

Running printf "%s is %d years old\n" Alice 14 displays the string "Alice is 14 years old," formatted exactly as specified, with a line break.

A common early mistake is not realizing, unlike echo, it doesn't add a line break automatically. If you want one, you need to explicitly include \n at the end of your format.

In real work, this is used inside shell scripts for formatting a table-style report, or displaying numbers with aligned digit widths.

Linux
Try it (type this into the pseudo terminal)
printf "%s is %d years old\\n" Alice 14

🧑‍💻 You can type this command into the Linux pseudo terminal to try it yourself (this page itself has no interactive terminal).

Ad space (banner)
Ad space (in-article)