How do I compare a variable to a string (and do something if they match)?
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.
Here, if we compare String1 and String2 using the = operator at first. As String1 and String2 both have the same length with the same sequence of characters, the comparison operator returns true and hence we get String1 and String2 are equal. as output from the first if-else block of the program.
You can check the equality and inequality of two strings in bash by using if statement. “==” is used to check equality and “!= ” is used to check inequality of the strings. You can partially compare the values of two strings also in bash.
You should not use == (equality operator) to compare these strings because they compare the reference of the string, i.e. whether they are the same object or not. On the other hand, equals() method compares whether the value of the strings is equal, and not the object itself.
if [ "$x" = "valid" ]; then echo "x has the value 'valid'" fi
If you want to do something when they don't match, replace =
with !=
. You can read more about string operations and arithmetic operations in their respective documentation.
$x
?You want the quotes around $x
, because if it is empty, your Bash script encounters a syntax error as seen below:
if [ = "valid" ]; then
==
operatorNote that Bash allows ==
to be used for equality with [
, but this is not standard.
Use either the first case wherein the quotes around $x
are optional:
if [[ "$x" == "valid" ]]; then
or use the second case:
if [ "$x" = "valid" ]; then
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