Reputation: 101
I have the following code, that I want to be inside an function getsum()
. I tried with the following code working without the function. When I run ./sum 5 6
I get 11
.
#!/bin/bash
sum=0
for i in $@; do sum=$((sum+i)); done
echo $sum
exit 0
But how can I put it in a function doing the same job?
I tried the following code but it doesn't work.
#!/bin/bash
sums() {
sum=0
for i in $@; do sum=$((sum+i)); done
echo $sum
exit 0
}
sums
Upvotes: 0
Views: 63
Reputation: 121347
You just need to pass the arguments ($@
) to the function sum()
that you pass to your script:
#!/bin/bash
sums() {
sum=0
for i in $@; do sum=$((sum+i)); done
echo $sum
exit 0
}
sums "$@" # Note this line
Upvotes: 3