I have problems on updating the value of a variable as follows: THE MAIN SCRIPT:
#!/bin/bash
meniu()
{
echo "Select operation: "
echo -e "1 - add\n2 - bbb\n3 - ccc\n4 - ddd\n5 - eee\n"
read input
case $input in
1)
add $@
echo "The result is: " $sum
;;
2)
scadere $@
echo "fgh: " $diferenta
;;
3)
inmultire $@
echo "fgh: " $produs
;;
4)
impartire $@
echo "hfg: " $cat
;;
5)
modulo $@
echo "fgh: " $rest
;;
*)
echo Execution finished!
sleep 6
return
;;
esac
fi
}
meniu $@
THE FUNCTION SCRIPT:
#!/bin/bash
add()
{
n=$#
sum=$1
for (( i=2; i<=n; i++ ))
do
sum=$((sum + i))
done
}
I just want to take the result returned by the add function and display it. The scripts are working but just for some values. I noticed that the adding goes bad when I use for arguments 1 1 or number smaller than my i (it starts from 2). I think that $((sum + i)) is the problem here. :( Any sugesstions please?
I think you used simple test input like 1 2 3 4. Your add function is not using your parameters (except the first one) for adding, but the value of the loop variable i:
What you were trying to do is dereferencing the variables:
I would choose another solution, I would use shift: