echo $SHELL
/bin/bash
echo $SHELL | wc -c
10
echo ${#SHELL}
9
The number of characters in $SHELL (e.g. /bin/bash) is 9, so why is the result is 10 when use wc -c?
echo $SHELL
/bin/bash
echo $SHELL | wc -c
10
echo ${#SHELL}
9
The number of characters in $SHELL (e.g. /bin/bash) is 9, so why is the result is 10 when use wc -c?
It's because of the newline added by echo. When you type:
$ echo $SHELL
/bin/bash
$
echo prints a newline character, which is counted in the wc character count.
On the other hand, ${#SHELL} is a shell expansion. The shell performs the character count using an expansion without the extra newline character since echo hasn't actually run yet. So echo ${#SHELL} actually translates to echo 9. The 9 is printed with a trailing new line added by echo.
I'm strongly recommend to use shell expansion. Here ${#SHELL}
Warning with wc -c that count BYTES. Not characters.
If you want to count characters with it, use wc -m
It's very important when you not only use ASCII chars table and an UTF-8 terminal (or whatever multibytes charset) or in I18N context
Try this:
$ x="/x/♤/é/"
$ echo ${#x}
$ echo -n "$x" | wc -c
$ echo -n "$x" | wc -m