I want to store the result of a bash string comparison in a variable, with effect equivalent to:
if [[ $a == $b ]]; then
res=1
else
res=0
fi
I was hoping to be able to write something terser, like:
res2=$('$a'=='$b') #Not valid bash
Is there a way to achieve what I want, without deferring to an if construct?
The need to compare strings in a Bash script is relatively common and can be used to check for certain conditions before proceeding on to the next part of a script. A string can be any sequence of characters. To test if two strings are the same, both strings must contain the exact same characters and in the same order.
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.
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.
I would suggest either:
res=0; [ "$a" == "$b" ] && res=1
or
res=1; [ "$a" == "$b" ] || res=0
Not quite as simple as you were hoping for, but does avoid the if ... else ... fi
.
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