0
0
Bash-scriptingHow-ToBeginner · 3 min read

How to Use printf in Bash: Syntax and Examples

In bash, printf formats and prints text using a format string and optional arguments. Use printf "format" arguments to control output layout precisely, unlike echo.
📐

Syntax

The basic syntax of printf in bash is:

  • printf FORMAT [ARGUMENT]...

Here, FORMAT is a string that specifies how to format the output, and ARGUMENTs are the values to print. Format specifiers like %s for strings and %d for integers control the output style.

bash
printf FORMAT [ARGUMENT]...
💻

Example

This example shows how to print a formatted string with a name and age using printf. It demonstrates string and integer formatting with placeholders.

bash
name="Alice"
age=30
printf "Name: %s, Age: %d\n" "$name" "$age"
Output
Name: Alice, Age: 30
⚠️

Common Pitfalls

Common mistakes include forgetting to escape newlines, not quoting variables, or mixing up format specifiers. For example, using echo when you need precise formatting or missing the newline \n can cause unexpected output.

Wrong usage example:

printf "Name: %s, Age: %d" $name $age

This may fail if variables contain spaces or special characters. Always quote variables:

printf "Name: %s, Age: %d\n" "$name" "$age"
📊

Quick Reference

Format SpecifierDescriptionExample
%sStringprintf "%s\n" "hello" # prints hello
%dInteger (decimal)printf "%d\n" 42 # prints 42
%fFloating point numberprintf "%.2f\n" 3.1415 # prints 3.14
\nNewline characterprintf "Line1\nLine2\n" # prints two lines
%%Literal percent signprintf "Progress: 50%%\n" # prints Progress: 50%

Key Takeaways

Use printf with a format string and arguments to control output precisely in bash.
Always quote variables in printf to avoid word splitting and errors.
Include \n in the format string to add newlines explicitly.
Use correct format specifiers like %s for strings and %d for integers.
printf is more reliable than echo for formatted output and scripting.