0

trying to make a basic addition function that adds the numbers entered and outputs a total. Here's my current function:

function addition() {
    read -a arr

    for i in ${arr[@]}
    do
        str=$str'+'$i

        echo $i
    done

    echo $str
}

but this seems to ask for one input then outputs the above. I've also tried using:

function addition() {
    for i in ${input[@]}

but that outputs an empty string. How do I go about creating a function that takes this command:

$ addition 4 3 13 40

into the function?

4

If your script/function takes the numbers on the command line, then you don't need to read them with read (which reads from standard input).

Instead:

addition () {
    sum=0

    for number do
        sum=$(( sum + number ))
    done

    printf 'Sum is %d\n' "$sum"
}

The loop could also be written more explicitly as

for number in "$@"; do
    sum=$(( sum + number ))
done

In both variations of the loop, the number variable will be assigned the value of each positional parameter ("command line argument") in turn, and the body of the loop will add these to the sum variable.

Note that the above code assumes that all command line arguments are integers without verifying that they are.


For fancier output:

addition () {
    sum=0

    for number do
        sum=$(( sum + number ))
    done

    ( IFS='+'; printf '%s = %d\n' "$*" "$sum" )
}

"$*" will expand to a single string consisting of the positional parameters concatenated with the first character of $IFS as delimiter.

Testing:

$ addition 1 2 3 90 32
1+2+3+90+32 = 128

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.