17

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?

4 Answers 4

27

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for the suggestion. I think in this form I would prefer to go with [ "$a" == "$b" ] && res=1 || res=0 as it has the more familiar c-style ternary structure.
5

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.

Comments

3
res2=$(expr "$a" == "$b")

Comments

1

Here is another option.

$> test "foo" = "bar"; res=$?
$> echo $res
1
$> test "foo" = "foo"; res=$?
$> echo $res
0

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.