如何迭代 while 参数循环以返回总和?

如何迭代 while 参数循环以返回总和?
if test $# -lt 1
then
        echo "Please input a valid amount of numbers. Need at least one."
        exit 1
else
        args=0
        while args -eq "$#"; do
                echo $args
                shift
        done
fi

echo $sum
echo $n

我收到的错误是

./whileParamList: 15: ./whileParamList: args: not found

while 循环将增加到前一个参数+=

答案1

Bash 不是为数值计算而设计的。这是一个协调者,不是 C 或 Python 意义上的“语言”。查看更多详细信息:


我这样做的方式是这样的:

mysum() (
  IFS=+
  bc<<<"$*"
)

也许:

mysum() (
  IFS=+
  echo "$(($*))"
)

然后像这样调用它:

$ mysum 5 89 83 7 0 2
186

答案2

像这样的事情我认为还可以:

if [[ $# -lt 1 ]]
then
        echo "Please input a valid amount of numbers. Need at least one."
        exit 1
else
        n=$#
        sum=0
        for arg in "$@"
        do
          echo "$arg"
          sum=$(($sum+$arg))
        done
fi

echo "sum=$sum"
echo "number of parameters=$n"

如果您更喜欢参数移位方法,这也可以:

if [[ $# -lt 1 ]]
then
        echo "Please input a valid amount of numbers. Need at least one."
        exit 1
else
        n=$#
        sum=0
        while [[ $# -ne 0 ]];
        do
          echo "arg=$1"
          sum=$(($sum+$1))
          shift
        done
fi

echo "sum=$sum"
echo "number of parameters=$n"

相关内容