I am new to Unix. I tried to add values as mentioned below:
var='expr 2 + 2' echo "Total value: $var" I expect the output to be Total value: 4. Instead I am getting Total value: expr 2 + 2.
Could anyone help me to identify my mistake?
Simplified approach :
var=$((2 + 2)) Or bc (calculator language) approach to perform math calculations:
var=$(echo '2 + 2' | bc) echo "Total value: $var" Total value: 4 expr is just fine. The important thing is the command substitution, using `command` or $(command)var=$((2 + 2)) is even better (portability). bc is good for extended math calculationsbc -l if you use decimal (non-integer) numbers.You need to know one shell concept: when you write var='expr 2 + 2', that's a string. But you want to have the result of this command. For that, you need to write $(expr 2 + 2) to execute the command, and substitute its output.
Here's a working replacement:
var=$(expr 2 + 2) echo "Total value: $var" Welcome to the Unix world! ;)
Another way:
var=$(( 2 + 2 )) echo "Total value: $var" (EDIT: not calling it a bashism)
$(( ... ))) are POSIX-compliant.