Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I evaluate an expression in bash and assign the value to a variable?

Tags:

bash

I have an expression like this:

if [[ $s == *Mar* ]]; then "match"; else "not"; fi;

How do assign its value to a variable? command substitution syntax does not work, because bash tries to evaluate the result of the expression:

x=$(if [[ $s == *Mar* ]]; then "match"; else "not"; fi;)

gives the error:

-bash: match: command not found  

So, basically I want to tell bash to evaluate an expression, but do not treat the output as a command. How do I do that?

like image 528
Salil Avatar asked Oct 21 '25 01:10

Salil


1 Answers

if [[ $s == Mar ]]; then "match"; else "not"; fi

is not an expression; it is a command. You could make it into a command that outputs either match or not by inserting appropriate echo commands, and then capture the output with backticks or $().

But that would be pointlessly indirect. Why not simply

if [[ $s == Mar ]]; then
  x="match"
else
  x="not"
fi

?

like image 91
hmakholm left over Monica Avatar answered Oct 23 '25 16:10

hmakholm left over Monica



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!