$ printf 'apple' | wc -m 5 $ echo 'apple' | wc -m 6
Why printf prints 5 and echo prints 6 characters?
Advertisement
Answer
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.