Linux bash. for loop and function, for adding numbers

I am studying a bash script on Linux, and I wanted to solve one problem that, in my opinion, would be easy, but I just can't figure it out.

I want to insert a number as a parameter, for example:

sh script.sh 5

And I want to get the result 15 if I insert 5 (1 + 2 + 3 + 4 + 5) = 15

I want to solve it using a function.

n=$1
result=0
j=0

ADD(){
    result=`expr $result + $j`
}

#for (( i=1; i<=$n; i++ ))
for i in {0..$n..1}
do 
    ADD
    j=`expr $j + $1`
done 

echo $result

Every time I want to add a number, I want to call a function to add. I can’t even imagine how right I am. And I do not know how to use for loop. I tried two different loops and I think they are not working correctly.

+4
source share
4 answers

Try the following:

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
+4
source

:

#!/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)"
+1

while :

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

$(.. whatever..) `..whatever..`, . , . for, $j -ne $n (j n) 1 j var .

+1

:

sum_to () ( 
    set -- $(seq $1)
    IFS=+
    echo "$*" | bc
)

sum=$(sum_to 5)
echo $sum         # => 15

:

$ time sum_to 1000000
500000500000

real    0m2.545s
user    0m2.513s
sys 0m0.189s

$ sum_to_2 () { { seq $1 | tr '\n' '+'; echo 0; } | bc; }
$ time sum_to_2 1000000
500000500000

real    0m0.727s
user    0m0.981s
sys 0m0.037s

:

$ sum_to_3 () { perl -le '$n=$ARGV[0]; $sum += $n-- while $n; print $sum' $1; }
$ time sum_to_3 1000000
500000500000

real    0m0.075s
user    0m0.071s
sys 0m0.002s

Worser: ""

$ sum_to_slow () { 
    sum=0
    for i in $(seq $1); do
        sum=$(expr $sum + $i)
    done
    echo $sum
}
$ date; time sum_to_slow 1000000; date
Mon Mar 17 14:00:53 EDT 2014
^C
$ date
Mon Mar 17 14:07:01 EDT 2014

Ctrl-C . , bash

$ sum_to_slow_improved () { sum=0; for i in $(seq $1); do (( sum += i )); done; echo $sum; }
$ time sum_to_slow_improved 1000000
500000500000

real    0m4.937s
user    0m4.869s
sys 0m0.124s

2 , Perl

0

Source: https://habr.com/ru/post/1532171/


All Articles