Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UNIX evaluate expression from a variable

Tags:

shell

unix

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.

like image 411
j.i.t.h.e.s.h Avatar asked Mar 23 '11 20:03

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


People also ask

How do you evaluate an expression in Unix?

The expr command in Unix evaluates a given expression and displays its corresponding output. It is used for: Basic operations like addition, subtraction, multiplication, division, and modulus on integers. Evaluating regular expressions, string operations like substring, length of strings etc.

How do I find the value of a variable in UNIX?

To find out if a bash variable is empty: Return true if a bash variable is unset or set to the empty string: if [ -z "$var" ]; Another option: [ -z "$var" ] && echo "Empty" Determine if a bash variable is empty: [[ ! -z "$var" ]] && echo "Not empty" || echo "Empty"

What is $_ in Unix?

$_ expands to the last argument to the previous simple command* or to previous command if it had no arguments. mkdir my-new-project && cd $_ ^ Here you have a command made of two simple commands. The last argument to the first one is my-new-project so $_ in the second simple command will expand to my-new-project .


1 Answers

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
like image 105
nobody Avatar answered Oct 11 '22 23:10

nobody