JohnnyTooBad
JohnnyTooBad

Reputation: 87

Bash not recognising strings as equal

I have two variables line and sorted, which are both space-delimited strings of numbers. Part of my script depends on checking whether these two strings are equal:

if [[ $sorted == $line ]]
then
echo "test"
fi

When running this I get no output. A visual check, using: echo $sorted and echo $line gives two seemingly similar outputs.

I thought that this may be due to either of the two outputs having an extra white space character at the end, so I decided to check whether removing spaces from the strings removed the problem:

test1=`echo $sorted | tr -d ' '`
test2=`echo $line | tr -d ' '`

Subsequently performing:

if [[ "$test1" == "$test2" ]]
then 
echo "test"
fi

Did give the desired "test" output. However, when comparing the number of characters of both variables using wc, the output is the same for both variables. Furthermore, checking the number of white space characters in line and sorted with echo <variable> | grep -o "\s" | wc -l also gives the same output for both variables.

My question is what could be causing this behaviour; running tr removes the problem, yet counting the number of white spaces with wc and grep shows that the number of spaces (or at least, characters) is similar.

Upvotes: 0

Views: 182

Answers (1)

Tom Fenech
Tom Fenech

Reputation: 74695

I think that some of your tests to see whether the strings are the same are broken, because you're not quoting your variables. This test should show a different count for the two variables:

echo "$var_name" | grep -c "\s"

You can use declare -p var_name to see the contents of your variable, which should show you where the leading/trailing white space is.

As you're using bash, you can also take advantage of the <<< here string syntax instead of using echo:

grep -c "\s" <<<"$var_name"

As kojiro points out in the comments (thanks), this is a more robust approach and saves creating a subshell.

Upvotes: 3

Related Questions