how can I add (subtract, etc.) two numbers with bash?
I can read the numbers and operation in with:
echo "First number please"
read num1
echo "Second number please"
read num2
echo "Operation?"
read op
but then all my attempts to add the numbers fail:
case "$op" in
"+")
echo num1+num2;;
"-")
echo `num1-num2`;;
esac
Run:
First number please
1
Second mumber please
2
Operation?
+
Output:
num1+num2
…or…
echo $num1+$num2;;
# results in: 1+2
…or…
echo `$num1`+`$num2`;;
# results in: ...line 9: 1: command not found
Seems like I’m getting strings still perhaps when I try add add (“2+2” instead of “4”).
Arithmetic in POSIX shells is done with $
and double parentheses (( ))
:
echo "$(($num1+$num2))"
You can assign from that; also note the $
operators on the variable names inside (())
are optional):
num1="$((num1+num2))"
There is also expr
:
expr $num1 + $num2
In scripting $(())
is preferable since it avoids a fork/execute for the expr
command.
The existing answer is pure bash, so it will be faster than this, but it can only handle integers. If you need to handle floats, you have to use the external program bc
.
$ echo 'scale=4;3.1415+9.99' | bc
13.1315
The scale=4
tells bc
to use four decimal places. See man bc
for more information.
echo `expr $a + $b`
echo `expr $a - $b`
echo `expr $a * $b`
echo `expr $a / $b`
Note the before the
*
(for multiplication),
the whole expression has to be within the backquotes `.
minimalist
total=0
((total+=qty))
Based on the sequence of inputs you request from the user, it seems you are using reverse polish notation.
echo "First number please" read num1 echo "Second number please" read num2 echo "Operation?" read op
You may do better just to use dc
(desk calculator) directly, since that is what it is for.
DESCRIPTION
Dc is a reverse-polish desk calculator which supports unlimited pre-
cision arithmetic.
Example session using dc
:
$ dc
1 2 + p # This part is typed; the result comes next.
3
q # This is also typed.
$
Or, non-interactively:
$ dc -e '1 2 + p'
3
$
You can also use $[ ... ]
structure. In this case, we use built-in mechanizm in Bash, which is faster and a bit more convenient to use. Since we know that everything between $[, and ] is treated as an expression, we don’t need to precede the variables with $
. Similarily, we do not need to secure *
from treating it like a pattern.
num1=2
num2=3
echo $[num1 + num2]
5