Pebellslearn by building
0%
RoadmapsMatrixCoursesSandboxSign in
Input and Output  ›  Lesson

printf for Tidy Output

printf formatting 12 minprintf prints its arguments through a format string with placeholders such as %s and %d, reuses the format until every argument is used, and adds no newline unless asked.

printf for Tidy Output

backup.sh finishes by listing each folder and how many files it saved. With echo, the numbers wobble left and right depending on the name's length. printf lets you say exactly how wide each column is, and it behaves the same on every system.

The rule

printf fills a format, reuses it for leftover arguments, and adds no newline.

The first argument is the format; the rest fill its placeholders in order:

printf '%-12s %6s\n' "Folder" "Files"
printf '%-12s %6d\n' notes 42 code 318
Folder        Files
notes            42
code            318

The pieces:

  • %s a string, %d a whole number, %f a decimal number, %% a literal percent sign.
  • A number sets a width: %6d pads to 6 characters, right-aligned.
  • A minus sign left-aligns: %-12s.
  • A dot sets precision: %.2f gives two decimals, so 3.14159 prints as 3.14.
  • \n is a newline and \t a tab. printf never adds a newline for you.

The second line above has one format and four arguments. printf used notes 42 for the first pass, then reused the format for code 318. That makes printing a list trivial: printf '%s\n' "${dirs[@]}" prints one folder per line.

Put the format in single quotes so Bash leaves the % and \ alone, and pass values as separate arguments rather than pasting them into the format.

The shortcut

Read a format as a row of slots: count the placeholders, then deal the arguments into them like cards, starting a new row whenever the slots run out.

printf '%s=%d;' a 1 b 2 cStep 1 of 4
  1. Count the slots

    Two: a %s and a %d.

Drills

Answer fast — trust the rule.

quick drill

What does printf '%s-' a b c print?

quick drill

What does printf '[%5s]' ab print?

quick drill

What does printf '%.2f\n' 3.14159 print?

quick drill

After printf 'Done', your prompt appears on the same line. Why?

Remember

  • printf fills a format, reuses it for leftover arguments, and adds no newline.
  • Width %6d right-aligns, %-12s left-aligns, %.2f sets decimals.
  • Deal arguments into slots like cards; single-quote the format.

Practice — level up

0/1 solved

Write your answer, then compare it with a rubric and a model answer.

ExplainA tidy summary table

backup.sh should end with a two-column report: folder names left-aligned in 12 characters and file counts right-aligned in 6. Write the printf lines for a header and the rows notes 42 and code 318, and explain the format pieces and why one printf can print both rows.