8

I have a variable which has a math expression. I want to evaluate it in UNIX shell and store the result in another variable. how do i do that ?

i tried the following but it doesn't works

var1="3+1"
var2=`expr "$var1"`
echo $var2

the var2 value should be calculated as 4.

6 Answers 6

8

You can do it this way

var2=$(($var1))
Sign up to request clarification or add additional context in comments.

Comments

6

expr requires spaces between operands and operators. Also, you need backquotes to capture the output of a command. The following would work:

var1="3 + 1"
var2=`expr $var1`
echo $var2

If you want to evaluate arbitrary expressions (beyond the limited syntax supported by expr) you could use bc:

var1="3+1"
var2=`echo $var1 | bc`
echo $var2

1 Comment

Please don't use backticks in shell scripts, whenever possible. Use command-substitution $().
2
eval "var2=\$(( $var1 ))"

Using built-in shell arithmetic avoids some complexity and expr's limited parser.

Comments

1

Try with backticks:

var2=`expr $var1`

Edit: you'll need to include spaces in your equation for expr to work.

2 Comments

yes, I had missed the part where he didn't include spaces. And I'm guessing he did have the backticks and they just got eaten because he didn't quote the code, so I'll give Andrew a plus one for beating me to the right answer.
Please don't use backticks in shell scripts. It's almost always better to use command-substitution $().
0

If these are mathematical expressions:

var2=$( bc <<< "$var1" )

or, for older shells

var2=$( printf "%s\n" "$var1" | bc )

Comments

0

Try using this syntax:

var1="3+1"
var2=$((var1))
echo $var2

output is: 4

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.