Reputation: 4508
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.
Upvotes: 8
Views: 48911
Reputation: 785611
Try using this syntax:
var1="3+1"
var2=$((var1))
echo $var2
Upvotes: 0
Reputation: 247012
If these are mathematical expressions:
var2=$( bc <<< "$var1" )
or, for older shells
var2=$( printf "%s\n" "$var1" | bc )
Upvotes: 0
Reputation: 264406
Try with backticks:
var2=`expr $var1`
Edit: you'll need to include spaces in your equation for expr to work.
Upvotes: 1
Reputation: 61449
eval "var2=\$(( $var1 ))"
Using built-in shell arithmetic avoids some complexity and expr
's limited parser.
Upvotes: 2
Reputation: 20174
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
Upvotes: 6