- Published on
A Clear Comparison Between `echo` and `printf` in Shell Scripting
- Authors

- Name
- hwahyeon
Comparison of echo and printf
In shell scripting, the echo and printf commands are commonly used for output, but they differ significantly in functionality and behavior.
1. Basic Functionality
echois used for simple output of strings or variable values. It's useful for quickly displaying results without formatting.printfprovides precise control over the output format and works similarly to theprintffunction in C.
Example
echo "Hello, world!" # Outputs: Hello, world!
printf "Hello, world!\n" # Outputs: Hello, world!
2. Escape Sequence Handling
echocan interpret escape sequences like\nor\twhen used with the-eoption in some shells like Bash. However, behavior varies between shells, and in some environments, the-emay be ignored or printed as plain text.printfalways 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
echoautomatically includes a newline (\n) at the end of the output. To suppress it, use the-noption.printfdoes not include a newline by default. You must explicitly add\nif needed.
Example
echo -n "No newline" # Outputs: No newline (no line break)
printf "No newline" # Outputs: No newline (no line break)
4. Complex Formatting
echocan only output plain text and doesn’t support formatting like decimal places or alignment.printflets 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
echobehaves differently depending on the shell. Options like-eand-nare not standardized by POSIX, which can lead to inconsistent results across systems.printfis 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