3

Kindly tell me that is it necessary to use "expr" keyword.

EG:-

 echo `expr a*b`

And where we can simply handle arithmetic expressions using simple arithmetic operators.

EG:-

echo a*b

Thanks in advance.

1
  • I am using bash shell.Is first method mentioned in question cannot be used for evaluating arithmetic expressions? Commented Jul 5, 2011 at 18:12

3 Answers 3

15

In a Posix shell you can evaluate expressions directly in the shell when they are enclosed in

$(( ... ))

So:

a=12
b=34
echo $(($a + $b))

And although this wasn't always the case, all Posix shells you are likely to encounter will also deal with:

echo $((a + b))

This all happened because, a long time ago, the shell did not do arithmetic, and so the external program expr was written. These days, expr is usually a builtin (in addition to still being in /bin) and there is the Posix $((...)) syntax available. If $((...)) had been around from day one there would be no expr.

The shell is not exactly a normal computer language, and not exactly a macro processor: it's a CLI. It doesn't do inline expressions; an unquoted * is a wildcard for filename matching, because a CLI needs to reference files more often than it needs to do arithmetic.

Sign up to request clarification or add additional context in comments.

Comments

6

The second form will almost surely never do what you want. In Bash, you have a built-in numeric expression handler, though:

A=4; B=6; echo $((A * B))

Comments

2

You can do arithmatic using $(())

echo $((2*3))

results in 6

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.