Q1How does printf differ from echo?
Formatted Output — printf
Unlike echo, printf adds no trailing newline, so you write \n yourself. Learn inserting values with %s/%d, aligning columns with \t, and creating multi-line files — hands-on in a browser terminal.
How printf Differs from echo — No Auto Newline
printf prints text just like echo, but unlike echo it doesn't add a trailing newline automatically.
You write \n yourself wherever you need a line break.
Since you can build the output exactly as you want, it's also good for creating multi-line files.
printf 'hello\n' prints hello and a newline.
Leave out \n and the next output continues on the same line.
Write it as printf 'a\nb\nc\n' > file and you create a 3-line file directly.
echo adds a trailing newline automatically; printf breaks lines only where you write \n.echo hello # hello + auto newline
printf 'hello\n' # hello + the newline you wrote
printf 'a\nb\nc\n' > letters.txt # create a 3-line file
cat letters.txt # the 3 lines a / b / c
| How to write it | Trailing newline | Result |
|---|---|---|
echo 'hi' | Added automatically | hi + newline |
printf 'hi' | Not added | just hi (no newline) |
printf 'hi\n' | Not added | hi + newline because you wrote \n |
Inserting Values and Aligning Columns — %s %d \t
Write %s (string) or %d (integer) in the format, and the values listed after it are inserted at those spots.
printf 'name=%s\n' alice prints name=alice.
It's better than simple concatenation with echo for fitting values into a fixed shape.
\t is a tab, used when you want to align columns.
The format is applied repeatedly, once for each set of values that follow.
Print a header and data each in a tab-separated format, like printf '%s\t%d\n' alice 30, and the columns line up.
%s inserts a string, %d an integer, and \t aligns columns with a tab.printf 'name=%s\n' alice # name=alice
printf '%s\t%s\n' name age # the header, tab-separated
printf '%s\t%d\n' alice 30 # a data row, aligned
| Symbol | Meaning | Example → output |
|---|---|---|
%s | Insert a string | printf '%s\n' hi → hi |
%d | Insert an integer | printf '%d\n' 42 → 42 |
\t | Tab (column alignment) | printf 'a\tb\n' → a + tab + b |
\n | Newline | printf 'x\n' → x + newline |
Knowledge Check
Answer each question one by one.
Q2What does printf 'name=%s\n' alice print?
Q3What does \t represent?