4

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
3
  • Could you please edit your question and format the code? Commented Jan 16, 2018 at 15:50
  • I am browsing from mobile I dont know how to do that Commented Jan 16, 2018 at 15:52
  • Very little needs to change. sum=$(( sum + number )) -- after changing your Read N and Sum=0 to read N and sum=0. Commented Jan 16, 2018 at 16:08

4 Answers 4

7

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

#! /bin/bash
read n
sum=0
for ((i=1; i<=n; i++)) ; do
   read number 
   ((sum+=number))
done
echo $sum
Sign up to request clarification or add additional context in comments.

Comments

0
#!/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}"

1 Comment

This is quite a lot of complexity to add functionality the OP didn't ask for.
0

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.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.