Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sum of integer variables bash script

Tags:

bash

shell

How can I do the sum of integers with bash script I read some variables with a for and I need to do the sum.

I have written the code like this:

Read N 
Sum=0
for ((i=1;i<=N;i++))
do
   read number 
   sum=sum+number
done
echo $sum
like image 510
Kate Avatar asked Oct 15 '25 12:10

Kate


1 Answers

Use the arithmetic command ((...)):

#! /bin/bash
read n
sum=0
for ((i=1; i<=n; i++)) ; do
   read number 
   ((sum+=number))
done
echo $sum
like image 194
choroba Avatar answered Oct 18 '25 08:10

choroba



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!