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 318Folder Files
notes 42
code 318The pieces:
%sa string,%da whole number,%fa decimal number,%%a literal percent sign.- A number sets a width:
%6dpads to 6 characters, right-aligned. - A minus sign left-aligns:
%-12s. - A dot sets precision:
%.2fgives two decimals, so3.14159prints as3.14. \nis a newline and\ta 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.
Count the slots
Two: a
%sand a%d.
Drills
Answer fast — trust the rule.
What does printf '%s-' a b c print?
What does printf '[%5s]' ab print?
What does printf '%.2f\n' 3.14159 print?
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
%6dright-aligns,%-12sleft-aligns,%.2fsets decimals. - Deal arguments into slots like cards; single-quote the format.
