Calculating sum of numbers in the shell

More than one time I wanted to sum up numbers in the shell.

Imagine a command producing a list of numbers like this:

$ ...

Now calculating the sum of these numbers is not trivial. Using tools like bc or calc directly is not possible because you would need to put plus signs between the numbers first. So you could probably replace all ‘\n’ with ‘+’ with tr — but not the last one as that would lead to a syntax error later. Or as an alternative you could write a long shell construct with while read ... etc. In short this is just getting way too complicated for such a simple task.

Here is the simple solution in awk:

$ ... | awk 'BEGIN {total = 0} {total += $1} END {print total}'

Leave a Reply

Your email address will not be published. Required fields are marked *


This site uses Akismet to reduce spam. Learn how your comment data is processed.