$ printf 'apple' | wc -m
5
$ echo 'apple' | wc -m
6
Why printf prints 5 and echo prints 6 characters?
They are both used to output data to the screen. The differences are small: echo has no return value while print has a return value of 1 so it can be used in expressions. echo can take multiple parameters (although such usage is rare) while print can take one argument. echo is marginally faster than print.”
print is faster than echo in the loops autobahn and hypertexts.
The echo command is used to display a line of text that is passed in as an argument. This is a bash command that is mostly used in shell scripts to output status to the screen or to a file.
The bash printf command is a tool used for creating formatted output. It is a shell built-in, similar to the printf() function in C/C++, Java, PHP, and other programming languages. The command allows you to print formatted text and variables in standard output.
First sentence of entry for echo
in the bash
man page (emphasis mine):
Output the args, separated by spaces, followed by a newline.
First sentence of the man page entry for printf
:
Write the formatted arguments to the standard output under the control of the format.
printf
only prints what appears in the format; it does not append an implied newline.
There may be other difference between echo "foo"
and printf "foo"
, depending on what exactly foo
is. The POSIX specification gives implementations broad discretion in how it implements echo
, probably to avoid choosing from among the diverse historical implementations as the standard. Use printf
when you rely on the precise output.
Here is the difference ..
$printf 'abcd'
abcd$ echo 'abcd'
abcd
$
As you can see the additional char is newline \n
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With