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

Why printf prints 5 and echo prints 6 characters?

codeforester
  • 39,467
  • 16
  • 112
  • 140
TheOneTeam
  • 25,806
  • 45
  • 116
  • 158

2 Answers2

13

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
  • 497,756
  • 71
  • 530
  • 681
  • 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
4

Here is the difference ..

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

As you can see the additional char is newline \n

riteshtch
  • 8,629
  • 4
  • 25
  • 38