Monday, December 17, 2012

Shell script: How to add multiple sequence numbers

This can be acheived in many ways.

Through for loop

Write a for loop using {}(know more about {} HERE) to mention the range of numbers and use let command to add those numbers. Below is the script which will uses for loop to add 1 to 100 numbers

#!/bin/bash

j=0
for i in {1..100}
do
let j=j+i
done
printf "Sum of 1 to 100 numbers is %d" $j

Explination: for will take each number in to i variable and adds up to j for each loop and give you the final result in j as shown in above printf command.
Note: Try to avoid echo command as much as possible as this is not protable.
Through while loop: Loop will continue while the condition is true.   #!/bin/bash
j=0
i=0
while [[ "$i" -le 100 ]]
do
let j=j+i,i++
done
printf "Sum of 1 to 100 numbers is %d" $j


Explination: While loop will check for condition that i less than equal to 100, the loop passes untill i reaches 100. let command is used to increment j and i. And then final value is stored in j.
Through untill loop: Untill loop is similar to while loop but in reverse. Loop will happen untill the condition is true.

#!/bin/bash

j=0
i=0
until [[ "$i" -gt 100 ]]
do
let j=j+i,i++
done
printf "Sum of 1 to 100 numbers is %d" $j



Through awk scripting.
seq 1 100 | awk '{ sum+=$1} END {print sum}'

Hope this helps to add multiple numbers for a given range.

0 comments:

Post a Comment