Kate
Kate

Reputation: 83

Sum of integer variables bash script

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

Upvotes: 4

Views: 13711

Answers (4)

PesaThe
PesaThe

Reputation: 7499

It is also possible to declare a variable as an integer with declare -i. Any assignment to that variable is then evaluated as an arithmetic expression:

#!/bin/bash

declare -i sum=0                           
read -p "Enter n: " n

for ((i=1; i<=n; i++)) ; do
   read -p "Enter number #$i: " number
   sum+=number #sum=sum+number would also work
done

echo "Sum: $sum"

See Bash Reference Manual for more information. Using arithmetic command ((...)) is preferred, see choroba's answer.


$ declare -i var1=1
$ var2=1

$ var1+=5
$ echo "$var1"
6

$ var2+=5
$ echo "$var2"
15

This can be a tad confusing as += behaves differently depending on the variable's attributes. It's therefore better to explicitly use ((...)) for arithmetic operations.

Upvotes: 0

choroba
choroba

Reputation: 241768

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

#! /bin/bash
read n
sum=0
for ((i=1; i<=n; i++)) ; do
   read number 
   ((sum+=number))
done
echo $sum

Upvotes: 7

Vinicius Placco
Vinicius Placco

Reputation: 1731

Well, not a straight bash solution, but you can also use seq and datamash (https://www.gnu.org/software/datamash/):

#!/bin/bash

read N
seq 1 $N | datamash sum 1

It is really simple (and it has its limitations), but it works. You can use other options on seq for increments different than 1 and so on.

Upvotes: 0

sahaquiel
sahaquiel

Reputation: 1838

#!/bin/bash

echo "Enter number:"
read N
re='^[0-9]+$'
if ! [[ ${N} =~ ${re} ]]
then
    echo "Error. It's not a number"
    exit 1
fi
Sum=0
for ((i=1;i<=N;i++))
do
sum=$((${sum} + ${i}))
done
echo "${sum}"

Upvotes: 0

Related Questions