Counting the characters inside a variable

Hi! I have a doubt about this topic…


“echo $variable | wc -c” #the output is 5. With wc -m is 5 also.

“echo ${#variable}” #the output is 4

I don’t understand why 5 in the first case.

Thanks in advance!!

Its becouse of the trailing newline / endline char. so your “test” is in effect a “test$” you can prove this with:
echo test > test.txt
and then open test.txt with vi and enter (in command mode) :set list to display whitespaces and endline chars.

to get rid of these you can use
echo -n "test"| wc -c
wich will give you the desired 4 chars.