0

Hi I'm trying to learn bash scripting and I just want to get the character count of a variable. I tried to do it using these two different methods, but I can't understand why I get a difference of one character? Thanks for the help.

chars="ABCDEFGHIJKLMNOPQRSTUVWXYZ"

echo ${#chars}
echo $(echo "$chars" | wc -c)

26
27

Charles Duffy
  • 280,126
  • 43
  • 390
  • 441
  • 2
    `echo` appends a newline unless invoked with `-n`, thus one more character – erik258 Oct 01 '22 at 14:56
  • 1
    There's no need for a command substitution in the second. Just use `echo "$chars" | wc -c`; all you are doing is capturing standard output from `wc` in order to immediately write it back to standard output. – chepner Oct 01 '22 at 16:06

1 Answers1

0

Within parentheses you wrote

echo "$chars" | wc -c

You want

echo -n "$chars" | wc -c

The -n suppresses trailing newline. As it stands, you are writing one additional character after the 26 letters, and wc is faithfully counting it.


Try this to see the effect of the -n flag.

echo -n abc; echo -n def
echo    uvw; echo    xyz
J_H
  • 17,926
  • 4
  • 24
  • 44
  • 2
    `echo -n` isn't POSIX-defined to do anything at all. `printf '%s' "$chars" | wc -c` is the better form. – Charles Duffy Oct 01 '22 at 16:09
  • (`-n` is the _only_ thing `echo` is allowed to treat as an option; any copy of `echo` that treats `echo -e` as an instruction to do anything other than print `-e` on output is noncompliant; and bash's echo can be configured to be more strictly standards-compliant in this respect; but while `-n` is allowed, it isn't defined by the standard to have any particular behavior). – Charles Duffy Oct 01 '22 at 16:10
  • Anyhow, _in bash_, run `set -o posix; shopt -s xpg_echo; echo -n` and you'll see `-n` written as output, not parsed as an option. Using `set -o` and `shopt -s` aren't the only way to get those options to be active -- they can be enabled through environment variables, or set as defaults at compile time, or in the `set -o posix` case enabled by starting the shell under the `sh` name. – Charles Duffy Oct 01 '22 at 16:11