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.
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.
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"
$_ 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 .
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With