Code example demonstrates addition of numbers in Bash shell

Three different solutions are available to achieve the desired output. The first solution involves a bash implementation that produces a specific output. The second solution suggests using awk and provides an explanation. The third solution assumes that the content is in a file and gives an output. For the third solution, two core utilities, namely ‘fold’ and ‘paste’, can be utilized to wrap the input line to a width of 1 character and merge the input sequentially with a delimiter. Finally, the sum can be calculated. An alternative to the second solution without using awk is also provided. Additionally, an awk one-liner example is given as a potential solution.


Solution 1:

Employ the arithmetic function with the code

((...))

.

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


Solution 2:

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


Solution 3:


Although there is no direct solution, an alternative is available that involves utilizing

seq

and

datamash

from the website https://www.gnu.org/software/datamash/.

#!/bin/bash
read N
seq 1 $N | datamash sum 1

The method is straightforward, although it does have drawbacks. Other settings can be applied to

seq

for alternative increments, among other things.

Frequently Asked Questions