Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Store bash string comparison in variable

Tags:

bash

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?

like image 721
cmh Avatar asked Nov 09 '12 16:11

cmh


People also ask

Can you compare strings in bash?

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.

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 I compare characters in bash?

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.


1 Answers

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.

like image 129
twalberg Avatar answered Sep 25 '22 23:09

twalberg