Why does “wc -c” print a value of one more with echo

echotext processingwc

When running

echo abcd | wc -c

it returns 5.
But the word abcd is only 4 characters long.

Is echo printing some special character after the word abcd?

And can I prevent echo from printing that?

Best Answer

echo print newline (\n) at end of line

echo abcd | xxd
0000000: 6162 6364 0a          abcd.

With some echo implementations, you can use -n :

-n do not output the trailing newline

and test:

echo -n abcd | wc -c
4

With some others, you need the \c escape sequence:

\c: Suppress the <newline> that otherwise follows the final argument in the output. All characters following the '\c' in the arguments shall be ignored.

echo -e 'abcd\c' | wc -c
4

Portably, use printf:

printf %s abcd | wc -c
4

(note that wc -c counts bytes, not characters (though in the case of abcd they are generally equivalent). Use wc -m to count characters).

Related Question