0

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?

2 Answers 2

4

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

2 Comments

OR echo $((a+b)) also
Right; inside an arithmetic expression, any string literal is assumed to be a variable to expand, so the dollar sign is optional for simple parameter expansions.
0
x=9
y=7
z=`expr $x + $y`
echo $z

Write the expression with spaces and surrounded with back-ticks (``).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.