5
$ printf 'apple' | wc -m
       5
$ echo 'apple' | wc -m
       6

Why printf prints 5 and echo prints 6 characters?

codeforester
  • 34,080
  • 14
  • 96
  • 122
TheOneTeam
  • 24,336
  • 44
  • 110
  • 154

4 Answers4

11

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.

chepner
  • 446,329
  • 63
  • 468
  • 610
  • Although the `echo` man page is relevant in so far as the bash built-in certainly was carefully crafted to perfectly emulate the program's behavior, `/bin/echo`, which the man page documents, is never executed in the OP's example. – Peter - Reinstate Monica Oct 29 '17 at 04:04
  • I'm referring to the `echo` entry in the `bash` man page, but it certainly is ambiguous. I'll clarify. – chepner Oct 29 '17 at 13:46
3

Here is the difference ..

$printf 'abcd'
abcd$ echo 'abcd'
abcd
$

As you can see the additional char is newline \n

riteshtch
  • 8,439
  • 4
  • 21
  • 36
0

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.

dburcu
  • 131
  • 5
-1

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:

!/bin/sh

a=0

while [ $a -lt 10 ] do printf $a a=expr $a + 1 done

o/p: 0123456789

Use of Echo:

!/bin/sh

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