Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is my bash string comparison of two identical strings always false?

I'm trying to write a simple little script to query a 3g connection, and if the connection has dropped, instigate a reconnection.

My problem is in checking the output of the command - two seemingly equal strings are not evaluated as equal. I'm sure there's a noob error in here somewhere!

#!/bin/bash

echo "Checking connection"
a="Not connected."
b=$(./sakis3g status --console)

if [[ "$a"!="$b" ]]; then 
    echo "Strings not equal:"
    echo "$a"
    echo "$b"
else 
    echo "Strings equal!!"
fi

The output when run:

user@mypc:~$ ./test_3g.sh 
Checking connection
Strings not equal:
Not connected.
Not connected.

When running ./test_3g.sh | cat -A:

user@mypc:~$ ./test_3g.sh | cat -A
Checking connection$
Strings not equal:$
Not connected.$
Not connected.$
like image 815
John Lyon Avatar asked Aug 29 '11 03:08

John Lyon


People also ask

How do you check if two strings are equal in Bash?

To check if two strings are equal in bash scripting, use bash if statement and double equal to== operator. To check if two strings are not equal in bash scripting, use bash if statement and not equal to!= operator.

How do I compare two string variables in Bash?

When comparing strings in Bash you can use the following operators: string1 = string2 and string1 == string2 - The equality operator returns true if the operands are equal. Use the = operator with the test [ command. Use the == operator with the [[ command for pattern matching.

How do you compare strings correctly?

The right way of comparing String in Java is to either use equals(), equalsIgnoreCase(), or compareTo() method. You should use equals() method to check if two String contains exactly same characters in same order. It returns true if two String are equal or false if unequal.

Do the comparison operators work on strings?

The comparison operators also work on strings. To see if two strings are equal you simply write a boolean expression using the equality operator.


1 Answers

You have to put spaces around operators:

if [[ "$a" != "$b" ]]; then ...

Without spaces you end up with a single string, equivalent to "$a!=$b". And testing just a string returns true if that string is non-empty...

like image 120
sth Avatar answered Oct 26 '22 23:10

sth