Store bash string comparison in variable

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.


You could also use the $? variable which contains the return value from the previous command:

res="$( [[ $a == $b ]]; echo $? )"

Although that would inverse the numbers you gave. The end result would be the same as:

if [[ $a == $b ]]; then
  res=0
else
  res=1
fi

That's because the shell interprets a return value of 0 as true and 1 as false.

Not saying I wholly advocate this solution either. It's hackish and a bit unclear. But it is terse and terse is what you asked for.

Tags:

Bash