$ printf \'apple\' | wc -m
5
$ echo \'apple\' | wc -m
6
Why printf prints 5 and echo prints 6 characters?
Echo command adds "\n" characters to the end of the string. That is, when we print something with the echo command, it automatically pass to the new line. But printf does not do this.
echo "string" equal to "string\n"and print "string" equal to "string".
so the output of "wc -m" command is different.
Here is the difference ..
$printf 'abcd'
abcd$ echo 'abcd'
abcd
$
As you can see the additional char is newline \n
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.
Printf does not give new line after execution of command but echo gives new linw after the execution of command. Please see the bewlow code output.
Use of Printf:
a=0
while [ $a -lt 10 ]
do
printf $a
a=expr $a + 1
done
o/p: 0123456789
Use of Echo:
a=0
while [ $a -lt 10 ]
do
echo $a
a=expr $a + 1
done
o/p:It will print in a column wise as this window not taking as a column wise please try to execute this code it will give better understanding.
0 1 2 3 4 5 6 7 8 9
you can remove the new line in echo by giving the bewlow command echo -n $a