I'm learning bash script's in Linux and I wanted to solve one problem that I thought it would be easy but I just cant figure it out.
I want to insert number as a parameter for example:
sh script.sh 5
And I want to get result 15 if I insert 5 (1+2+3+4+5)=15
I want to solve it with 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 when I want to add number I want to call function for adding. I have no idea if I even imagined right. And I don't know how to use for loop's. I've tried two different for loop's and I think they are not working correctly.
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)"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With