- Published on
A Clear Comparison Between `echo` and `printf` in Shell Scripting
- Authors
- Name
- hwahyeon
echo
and printf
Comparison of In shell scripting, the echo
and printf
commands are commonly used for output, but they differ significantly in functionality and behavior.
1. Basic Functionality
echo
is used for simple output of strings or variable values. It's useful for quickly displaying results without formatting.printf
provides precise control over the output format and works similarly to theprintf
function in C.
Example
echo "Hello, world!" # Outputs: Hello, world!
printf "Hello, world!\n" # Outputs: Hello, world!
2. Escape Sequence Handling
echo
can interpret escape sequences like\n
or\t
when used with the-e
option in some shells like Bash. However, behavior varies between shells, and in some environments, the-e
may be ignored or printed as plain text.printf
always interprets escape sequences by default and behaves consistently across different environments.
Example
echo -e "Line1\nLine2" # Line1 (newline) Line2
printf "Line1\nLine2\n" # Line1 (newline) Line2
3. Line Break Handling
echo
automatically includes a newline (\n
) at the end of the output. To suppress it, use the-n
option.printf
does not include a newline by default. You must explicitly add\n
if needed.
Example
echo -n "No newline" # Outputs: No newline (no line break)
printf "No newline" # Outputs: No newline (no line break)
4. Complex Formatting
echo
can only output plain text and doesn’t support formatting like decimal places or alignment.printf
lets you control the output format, such as showing numbers with a fixed number of decimal places.
Example
echo "Price: 3.14159" # Outputs: Price: 3.14159
printf "Price: %.2f\n" 3.14159 # Outputs: Price: 3.14
In the printf
example, %.2f
means “print the number with 2 digits after the decimal point.” This is helpful when you need cleaner, consistent output.
5. Portability
echo
behaves differently depending on the shell. Options like-e
and-n
are not standardized by POSIX, which can lead to inconsistent results across systems.printf
is a POSIX-standard command and behaves consistently on nearly all Unix-like systems, making it more reliable for portable scripts.
Example
echo -e "Tab\tSpace" # May interpret tab in Bash, may show -e literally in Dash
printf "Tab\tSpace\n" # Always outputs: Tab Space