6

I am having troubles with the arithmetic expressions in a bash file (a unix file .sh).

I have the variable "total", which consists of a few numbers separated by spaces, and I want to calculate the sum of them (in the variable "dollar").

#!/bin/bash
..
dollar=0
for a in $total; do
  $dollar+=$a
done

I know I am missing something with the arithmetic brackets, but I couldn't get it to work with variables.

sheldonzy
  • 5,505
  • 9
  • 48
  • 86
  • If I remember correctly, it is `$dollar=$(($dollar + $a))` – Azize Jul 18 '17 at 17:50
  • As you have it in a variable with space between values you can do like this also: `$dollar=$(echo $total | tr ' ' '+' | bc)` – Azize Jul 18 '17 at 17:55
  • 2
    Please take a look: http://www.shellcheck.net/ – Cyrus Jul 18 '17 at 17:56
  • Also see [Arithmetic expressions in Bash?](https://stackoverflow.com/q/2517727/608639), [How do I do if statement arithmetic in bash?](https://stackoverflow.com/q/8304005/608639), [How to use Shellcheck](http://github.com/koalaman/shellcheck), [How to debug a bash script?](http://unix.stackexchange.com/q/155551/56041) (U&L.SE), [How to debug a bash script?](http://stackoverflow.com/q/951336/608639) (SO), etc. – jww Sep 29 '19 at 20:49

2 Answers2

6

Wrap arithmetic operations within ((...)):

dollar=0
for a in $total; do
  ((dollar += a))
done
janos
  • 120,954
  • 29
  • 226
  • 236
5

There are a number of ways to perform arithmetic in Bash. Some of them are:

dollar=$(expr $dollar + $a)
let "dollar += $a"
dollar=$((dollar + a))
((dollar += a))

You may see more on the wiki. If you need to handle non-integer values, use a external tool such as bc.

ephemient
  • 198,619
  • 38
  • 280
  • 391