bash shell 脚本 + 数字总和

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3634012/
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-09 19:38:48  来源:igfitidea点击:

shell script + numbers sum

bashksh

提问by lidia

what the best simple elegant way to sum number in ksh or bash my example is about let command , but I want to find better way to summary all numbers

在 ksh 或 bash 中对数字求和的最佳简单优雅方法是什么,我的示例是关于 let 命令的,但我想找到更好的方法来总结所有数字

for example

例如

num1=1232
num2=24 
num3=444
.
.
.

let SUM=$num1+num2+num3.........

回答by codaddict

How about:

怎么样:

num1=1232
num2=24 
num3=444
sum=$((num1+num2+num3))
echo $sum # prints 1700

回答by jyz

Agree with ghostdog74. I once used $(( )) built-in function, but I changed to bc because the format the we receive data is not very "number-formated". Check below:

同意ghostdog74。我曾经使用过 $(( )) 内置函数,但是我改成 bc 是因为我们接收到的数据的格式不是很“数字格式”。检查以下:

jyzuz@dev:/tmp> echo $(( 017 + 2 ))
17
jyzuz@dev:/tmp> echo $(( 17 + 2 ))
19
jyzuz@dev:/tmp>

Seems that in the 1st case it understands as binary or hex numbers.. not very sure.

似乎在第一种情况下它理解为二进制或十六进制数..不太确定。

So I changed to bc. You can choose wich way you prefer:

所以我改为 bc。您可以选择您喜欢的方式:

bc << EOF
$num1 + $num2 + $num3
EOF

or

或者

bc <<< "$num1 + $num2 + $num3"

There are other cools ways to do this...but it would be good if you send more details, like if you're performing division also, you'll need to add bc -largument, to load math lib.

还有其他很酷的方法可以做到这一点......但是如果你发送更多细节会很好,比如如果你也在执行除法,你需要添加bc -l参数来加载数学库。

回答by Paused until further notice.

You can eliminate the last dollar sign and freely space the operands and operators (including the variable and the assignment operator) for readability if you move the double parentheses all the way to the outside.

如果您将双括号一直移到外面,您可以消除最后一个美元符号并自由分隔操作数和运算符(包括变量和赋值运算符)以提高可读性。

num1=1232
num2=24 
num3=444
(( sum = num1 + num2 + num3 ))

(( count++ ))

(( sum += quantity ))

You can't use the increment style operators (*= /= %= += -= <<= >>= &= ^= |= ++ --) unless you use letor the outside (())form (or you're incrementing variables or making assignments on the right hand side).

您不能使用增量样式运算符 ( *= /= %= += -= <<= >>= &= ^= |= ++ --) ,除非您使用let或 外部(())形式(或者您正在增加变量或在右侧进行赋值)。

回答by ghostdog74

you can use $(())syntax, but if you have decimal numbers, use awk, or bc/dc to do your maths, "portably".

您可以使用$(())语法,但如果您有十进制数,请使用 awk 或 bc/dc 进行数学运算,“可移植”。