j.i.t.h.e.s.h
j.i.t.h.e.s.h

Reputation: 4508

UNIX evaluate expression from a variable

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

Answers (6)

anubhava
anubhava

Reputation: 785611

Try using this syntax:

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

output is: 4

Upvotes: 0

glenn jackman
glenn jackman

Reputation: 247012

If these are mathematical expressions:

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

or, for older shells

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

Upvotes: 0

BMitch
BMitch

Reputation: 264406

Try with backticks:

var2=`expr $var1`

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

Upvotes: 1

amit_g
amit_g

Reputation: 31260

You can do it this way

var2=$(($var1))

Upvotes: 8

geekosaur
geekosaur

Reputation: 61449

eval "var2=\$(( $var1 ))"

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

Upvotes: 2

nobody
nobody

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

Related Questions