I am writing a program on using wc -m/wc -c to count the amount of letters in a string. It counts the letters, but adds one extra. This is what I currently have:

echo "enter a word"
read var1
echo $var1 | wc -c

When I enter the word, it successfully does something, however, for example if I enter "test" it will output 5.

Why is it doing this and is there a fix?


This has to do with the command you're using to pipe the string to wc. The echo command is slipping in an extra character at the end of your string, test, a new newline character, \n.

So in effect you're counting this: test\n. You can disable this behavior with the -n switch to echo.

$ echo -n "test" | wc -c

Or use a different command to generate your string, such as printf:

$ printf "%s" "test" | wc -c

Seeing what's happening

You can use od to see the actual characters that are getitng passed to the pipe like so:

$ echo "test" | od -c
0000000   t   e   s   t  \n

$ echo -n "test" | od -c
0000000   t   e   s   t

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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