Skip to the workspace
Pebellslearn by building
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.

shell bash / printf for Tidy Output

Explore each scene at your own pace.

01 · The rule

The rule

printf for Tidy Output

printf 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.

Keep the format string fixed and pass untrusted text as data arguments.

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.

Scene 1 of 5
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.