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.
Latest posts by Surendra Anne (see all)
- Docker: How to copy files to/from docker container - June 30, 2020
- Anisble: ERROR! unexpected parameter type in action:
Fix - June 29, 2020 - FREE: JOIN OUR DEVOPS TELEGRAM GROUPS - August 2, 2019
- Review: Whizlabs Practice Tests for AWS Certified Solutions Architect Professional (CSAP) - August 27, 2018
- How to use ohai/chef-shell to get node attributes - July 19, 2018