Reputation: 1765
Following is the code that I tried -
nisarg@nisarg-ThinkPad-T61:~$ export a=1
nisarg@nisarg-ThinkPad-T61:~$ export b=2
nisarg@nisarg-ThinkPad-T61:~$ echo $a
1
nisarg@nisarg-ThinkPad-T61:~$ echo $b
2
nisarg@nisarg-ThinkPad-T61:~$ echo 'expr $a + $b'
expr $a + $b
I even made sure there are spaces around +
as they are the cause of most errors.
Why isn't this working?
Upvotes: 0
Views: 6072
Reputation: 367
x=9
y=7
z=`expr $x + $y`
echo $z
Write the expression with spaces and surrounded with back-ticks (``).
Upvotes: 0
Reputation: 532053
The single quotes prevent $a
and $b
from being expanded, as well as expr
from being called; you may be confusing single quotes with backquotes, which are the older syntax for command substitution. Use double quotes and $( ... )
:
echo "$(expr $a + $b)"
The above code is equivalent to
expr $a + $b
so you only need the command substitution if you need to capture the output to assign to a variable or to embed the result in a longer string. Also, expr
is unnecessary for arithmetic in a POSIX-compatible shell (i.e., almost any shell you are likely to be using). You can use an arithmetic expression $(( ... ))
instead.
echo "$(( $a + $b ))"
Upvotes: 4