I'm working on a Bash script and the length of the string contained in a certain variable is one of my conditions. The current string is W5u7TBTzF17GGFV8DBJHvgAAAAI. Initially I've count the string length by the help of wc -c:

$ VAR='W5u7TBTzF17GGFV8DBJHvgAAAAI'; echo "$VAR" | wc -c

But my script condition [[ ${#VAR} -eq 28 ]] never pass. Then I decided to count the characters on by one. Indeed the string length is 27 characters, also the value of ${#VAR} is 27:

$ echo "${#VAR}"

So I'm in wondering - where does this difference come from?

  • 4
    This echo -n ${VAR} | wc -c give 27, so newline character is there – George Udosen Sep 14 '18 at 22:07
  • 1
    @GeorgeUdosen, probably this should be the answer :) – pa4080 Sep 14 '18 at 22:11

It's the way echo works. Now do

echo koko

You get

georgek@georgek-HP-Pavilion-17-Notebook-PC:~$ echo koko

But do echo -n koko and you get

georgek@georgek-HP-Pavilion-17-Notebook-PC:~$ echo -n koko

So wc is capturing the newline character too. Use

echo -n "${VAR}" | wc -c

To get the desired result. The echo command will add the newline character, so that gets counted too. To remove this and get the real count use the -n option.

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.