printf
printf is like filling in a form with blanks for names and numbers, so your output comes out exactly the shape you planned. Unlike echo, it will not press Enter for you at the end.
In this page:
Syntax
printf "format string\n" argument1 argument2
# %s string, %d integer, %.2f decimal
printf
printf formats output using format specifiers like %s (string), %d (integer), and %.2f (decimal), similar to C's printf. Unlike echo, it does not add a trailing newline automatically — you must include \n yourself.
It gives much more precise control over output formatting than echo.
Note:
Use
printf instead of echo whenever you need aligned columns or fixed decimal places.Example: printf
#!/bin/bash
printf "Name: %s, Age: %d\n" "Alice" 30
printf "Pi is approximately %.2f\n" 3.14159
printf "%-10s|%5s\n" "left" "right"
Login to try C/C++/Java/PHP code in the editor
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the
view already swaps in the hi_ translation fields (or blanks these
out if untranslated), so this renders correctly for both languages
without a lang_code check here. #}
Common Mistakes
- Forgetting
\nin the format string, sinceprintfdoes not add a newline by itself. - Passing the wrong number of arguments, so the format is reused or fields are empty.
- Using user input as the format string, as in
printf "$input", which can break on%; useprintf '%s\n' "$input".
🔒
Chapter Quiz — Complete all 14 topics to unlock
0/14 topics done
Complete these topics first: