Hi! If you're new here, you may want to subscribe to the Unix Tutorial RSS feed to get regular tips & tricks for all flavors of Unix. You can follow me on Twitter, too! Thanks for visiting!
If you're ever thought of summing up more than two numbers in shell script, perhaps this basic post will be a good start for your Unix scripting experiments.
Basic construction for summing up in shell scripts
In my Basic arithmetic operations in Unix shell post last year, I've shown you how to sum up two numbers:
SUM=$(($NUMBER1 + $NUMBER2)
using the same approach, it's possible to calculate sums of as many numbers as you like, if you use one of the loops available in your shell.
Before we get started, let's create a simple file with numbers we'll work with:
ubuntu$ for i in 1 2 3 4 5 6 7 8 9; do echo $i >> /tmp/nums; done; ubuntu$ cat /tmp/nums 1 2 3 4 5 6 7 8 9
Using a while loop to sum numbers up in Unix
Here's an example of how you can use a while loop in Unix shell for summing numbers up. Save it as a /tmp/sum.sh script, and don't forget to do chmod a+x /tmp/sum.sh so that you can run it!
#!/bin/sh
#
SUM=0
#
while read NUM
do
echo "SUM: $SUM";
SUM=$(($SUM + $NUM));
echo "+ $NUM: $SUM";
done < /tmp/nums
Here's how the output will look when you run it:
ubuntu$ /tmp/sum.sh SUM: 0 + 1: 1 SUM: 1 + 2: 3 SUM: 3 + 3: 6 SUM: 6 + 4: 10 SUM: 10 + 5: 15 SUM: 15 + 6: 21 SUM: 21 + 7: 28 SUM: 28 + 8: 36 SUM: 36 + 9: 45
Of course, your data will most probably will be in a less readable form, so you'll have to do a bit of parsing before you get to sum the numbers up, but the loop will be organized in the same way.
That's it for today, enjoy and feel free to ask questions!











3 comments ↓
Hello,
Can you please provide the following codes:
1. I divide 20 /6 . The answer id now 3. It sould be 3.33
2. How to do 10.222 + 1.1 = 11.322
Thanks in advance.
[...] Summing numbers up in Unix scripts [...]
Hello Ankan,
you need to use "scale" option from bc:
echo 'scale=25;57/43′ | bc
Scale controls the number of decimal points. Not sure if scale is an option, command or what not… but that's your answer.
Regards,
Pete
Leave a Comment