Linux bash. for loop and function, for adding numbers

Try this:

n=$1

sum=0
for i in `seq 1 $n` ; do
    ## redefine variable 'sum' after each iteration of for-loop
    sum=`expr $sum + $i`
done

echo $sum

With a while loop and similar to your code:

#!/bin/bash

n=$(expr $1 + 1)
result=0
j=0

add(){
    result=$(expr $result + $j)
}

while test $j -ne $n
do
    add
    j=$(expr $j + 1)
done

echo $result

The $(..whatever..) is similar to `..whatever..`, it executes your command and returns the value. The test command is very usefull, check out the man. In this case simulates a for loop comparing the condition $j -ne $n (j not equal n) and adding 1 to the j var in each turn of the loop.


You could try below:

#!/usr/bin/env bash

sumit() {
    local n=$1
    local sum=0
    for (( i=0;i<=n;i++ )) ; do
        (( sum = sum + i ))
    done

    echo "$sum"
}

sum=$(sumit $1)
echo "sum is ($sum)"