Bash: calculate sum from a list of numbers

Getting the sum of a list of numbers is a common scenario on the command line, whether you are checking local filesystem utilization or parsing infrastructure reports for total cpu counts.

There are multiple ways this can be done, but one of the simplest is to use awk.  Let’s use a a sequence of numbers from 1 to 3 as an example.

$ seq 1 3
1
2
3

# get the sum of the numbers
$ seq 1 3 | awk 'BEGIN{sum=0}{sum+=$1}END{print sum}'
6

The same command works for floating point numbers as well.

# use awk to multiply by 1.25 for floating point
$ seq 1 3 | awk {'printf "%f\n", $1*1.25'}
1.250000
2.500000
3.750000

# get the sum of floating point numbers
$ seq 1 3 | awk {'printf "%f\n", $1*1.25'} | awk 'BEGIN{sum=0}{sum+=$1}END{print sum}'
7.5

Of course, there are other ways this could be done, for example here is ‘bc

# bc is not installed by default on every distribution
sudo apt install -y bc

# construct valid math expression
seq 1 3 | awk {'printf "%f+", $1*1.25'} | sed 's/$/0.0\n/'

# evaluate with bc
seq 1 3 | awk {'printf "%f+", $1*1.25'} | sed 's/$/0.0\n/' | bc

 

REFERENCES

awk man page

bc man page

askubuntu, sum numbers from file