bash 计算命令行参数的总和并显示结果

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16757510/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 05:31:05  来源:igfitidea点击:

Calculate sum of command line arguments and display the result

bash

提问by classA

Write a bash script that adds its command line arguments and display the result. Assume command line arguments are all integers apart from the argument itself.

编写一个 bash 脚本,添加其命令行参数并显示结果。假设命令行参数除了参数本身之外都是整数。

So for example:

例如:

% addprogram 2 5 7
The total is 14

I've tried all I can and can't seem to find anything on the net, please keep the answer really simple.

我已经尽我所能,但似乎在网上找不到任何东西,请保持答案非常简单。

I've tried stuff like:

我试过这样的东西:

#!/bin/bash

total += $@

But I don't think that operator exists in bash.

但我不认为该运算符存在于 bash 中。

My algorithm would be something like this:

我的算法是这样的:

  1. For argument passed from the command line,
  2. Add the first argument to the total,
  3. move onto the next argument and add that to the total,
  4. repeat as long as there are arguments
  5. output total
  1. 对于从命令行传递的参数,
  2. 将第一个参数添加到总数中,
  3. 转到下一个参数并将其添加到总数中,
  4. 只要有参数就重复
  5. 总产量

回答by

Because nobody's done it yet

因为还没有人做过

IFS=+
bc<<<"$*"

Using bcgets you bignums; shell builtin arithmetic fails when the numbers are huge.

使用bc让你大数;当数字很大时,shell 内置算术失败。

exprmay or may not do bignums depending on whether it's a recent GNU coreutils version.

expr可能会或可能不会做 bignums,这取决于它是否是最近的 GNU coreutils 版本。

The IFSand <<<are just tricks to make it shorter. A more understandable version would be

IFS<<<只是技巧,使其更短。一个更容易理解的版本是

echo $* | sed 's/ /+/g' | bc

回答by Micha? ?rajer

posix compatible version:

posix 兼容版本:

for i do
    sum=$(expr $sum + $i)
done
echo $sum

Note that by default foriterates over $@.

请注意,默认情况下for迭代$@.

回答by mogul

Something like this?

像这样的东西?

for n in $@
do
  let sum=$sum+$n
done
echo The total is $sum

回答by Micha? Kosmulski

I like awk, so I'd do it like this:

我喜欢awk,所以我会这样做:

echo $@ | tr ' ' '\n' | awk '{sum+=
echo $@ | tr ' ' '\n' | ( sum=0; while read; do sum=$((sum+REPLY)); done; echo $sum )
}END{print sum}'

And a pure-bash version could go like:

一个纯 bash 版本可能是这样的:

sum=0
while [ -n "" ]; do
    sum=`expr $sum + `
    shift
done
echo $sum

回答by Adam Siemion

Following the steps you have provided, with shiftand expr:

按照您提供的步骤,使用shiftexpr

total=0

for i in $@; do
  (( total+=i ))
done

echo "The total is $total"

回答by Ansgar Wiechers

I'd do it like this:

我会这样做:

##代码##