0

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
1
  • Apart from exit 0 your function looks fine. That statement will terminate your shell! Commented Oct 10, 2015 at 20:30

1 Answer 1

3

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.