4

I've created script, where I encoded string 28 times with base64. Then I wanted to echo count of chars in outputted string.

First I used ${#var} which gave me 34070.

Then I tried on the same string

script.sh | wc -c

which gave me 34071.

#!/bin/bash
var="9M"
for i in {1..28};do
var=$(echo $var | base64)
done
echo ${#var}

What exactly does make those two outputs different?

2

2 Answers 2

5

As you can see in this example using the command od showing the bytes, it prints the newline:

$ echo foo | od -c -b
0000000   f   o   o  \n
        146 157 157 012
0000004

So in this case, wc -c as well as wc -m is counting the newline.

Without the newline:

$ echo -n foo | od -c -b
0000000   f   o   o
        146 157 157
0000003

So if you use echo, add the -n option so it doesn't print the newline, or printf:

$ printf "%s" foo | od -c -b
0000000   f   o   o
        146 157 157
0000003

0
3

The extra character is the newline. You can see it if you do, for example:

echo $var | hd | tail
2
  • 1
    I don't know what hd is (it's not in any package of my distro, at least), but od is part of POSIX and available in GNU's coreutils.
    – JoL
    Mar 17, 2021 at 0:47
  • @JoL you can do then echo $var | od -Ax -t x1z | tail and get an output similar to that of hd. Mar 17, 2021 at 1:16

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .