1

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?

0

4 Answers 4

3

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 
Sign up to request clarification or add additional context in comments.

4 Comments

Looks like overkill to me - expr is just fine. The important thing is the command substitution, using `command` or $(command)
@TobySpeight, var=$((2 + 2)) is even better (portability). bc is good for extended math calculations
Remember to use bc -l if you use decimal (non-integer) numbers.
I always forget that arithmetic substitution is standard - it always seems like the kind of thing that would be Bash-only for some reason.
3

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! ;)

Comments

1
var=$(expr "2" + "2") echo "Total value: $var" 

Comments

-1

Another way:

var=$(( 2 + 2 )) echo "Total value: $var" 

(EDIT: not calling it a bashism)

3 Comments

bashism? Really?
Arithmetic expansions ($(( ... ))) are POSIX-compliant.
Thanks, I updated the answer accordingly, not calling it a bashism anymore.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.