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.$
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.
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.
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.
The comparison operators also work on strings. To see if two strings are equal you simply write a boolean expression using the equality operator.
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...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With