0

I was finding length of a variable as below:

`set num=123456`
`echo $num|wc -c`

it returned output as 7 (suppose to return 6)

I did same with printf

`printf "%s" $num|wc -c`

it returned output as 6 ( as expected)

Does echo considering null character while counting? is Printf counting till null character?

what is so special about printf?

Aravind
  • 1,599

1 Answers1

4

The easiest way to see this is to use something like od -c which prints all characters:

$ echo 123456 | od -c
0000000   1   2   3   4   5   6  \n
0000007
$ printf 123456 | od -c
0000000   1   2   3   4   5   6
0000006

As you can see, echo prints an extra \n but printf doesn't. wc -c counts bytes, it doesn't care whether the character in question can be seen by humans or not, it just counts the number of bytes in its input.

As for what's so special about printf vs echo, see here for more details than you ever wanted to know.

terdon
  • 242,166
  • If bash did not introduce an incompatible behavior with echo around 1990, echo would be usable...but bash introduced echo -e that is not covered by POSIX (only echo -n triggers unspecified behavior). – schily May 31 '16 at 12:11