How to add arguments on a variable?

2019-09-09 22:57发布

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?

标签: linux bash
1条回答
淡お忘
2楼-- · 2019-09-09 23:25

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:

add()
{
    n=$#
    sum=$1

    for (( i=2; i<=n; i++ ))
    do
        sum=$((sum + i))
    done
}

add 1 2 3 4
echo "All seems well: sum=${sum}"
add 4 4 4
echo "I want 12, I got: sum=${sum}"

What you were trying to do is dereferencing the variables:

add()
{
    n=$#
    sum=$1

    for (( i=2; i<=n; i++ ))
    do
        sum=$((sum + ${!i}))
    done
}

add 1 2 3 4
echo "All seems well: sum=${sum}"
add 4 4 4
echo "I want 12, I got: sum=${sum}"

I would choose another solution, I would use shift:

add()
{
    sum=0
    while [ $# -gt 0 ]; do
        sum=$((sum + $1))
        shift
    done
}

add 1 2 3 4
echo "All seems well: sum=${sum}"
add 4 4 4
echo "I want 12, I got: sum=${sum}"
查看更多
登录 后发表回答