Bash Scripting – Add or Subtract Two Numbers

bashscriptingvariable

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").

Best Answer

Arithmetic in POSIX shells is done with $ and double parentheses (( )):

echo "$(($num1+$num2))"

You can assign from that (sans echo):

num1="$(($num1+$num2))"

There is also expr:

expr $num1 + $num2

In scripting $(()) is preferable since it avoids a fork/execute for the expr command.

Related Question