做加法的shell函数

写了一个对所有传入的参数做加法的shell函数,贴上来,给大家参考。

没有做什么异常处理,利用bc来计算

function calc_sum()
{
    if [ $# -lt 1 ]; then
        echo 0
        return 0
    fi

    local __SUM_STR="scale=2;"
    local __VAR_COUNT=$#
    for i in `seq 1 $#`; do
        __SUM_STR="$__SUM_STR \$$i +"
    done

    #### cut the last  +
    __SUM_STR=${__SUM_STR%+*}

    #### cal the sum
    eval echo "\"$__SUM_STR\"" | bc
}

Leave a Reply