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?

  • 1
    The echo is also printing a newline, printf is not. – 123 May 31 '16 at 9:06
up vote 4 down vote accepted

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.

  • 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

Your Answer

 

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Not the answer you're looking for? Browse other questions tagged or ask your own question.