she*_*nzy 6 bash arithmetic-expressions
我在处理 bash 文件(unix 文件 .sh)中的算术表达式时遇到问题。
我有变量“total”,它由几个用空格分隔的数字组成,我想计算它们的总和(在变量“dollar”中)。
#!/bin/bash
..
dollar=0
for a in $total; do
$dollar+=$a
done
Run Code Online (Sandbox Code Playgroud)
我知道我遗漏了算术括号中的一些内容,但我无法让它与变量一起使用。
将算术运算包含在((...)):
dollar=0
for a in $total; do
((dollar += a))
done
Run Code Online (Sandbox Code Playgroud)
在 Bash 中执行算术运算的方法有很多种。他们之中有一些是:
dollar=$(expr $dollar + $a)
let "dollar += $a"
dollar=$((dollar + a))
((dollar += a))
Run Code Online (Sandbox Code Playgroud)
您可能会在wiki上看到更多内容。如果您需要处理非整数值,请使用外部工具,例如bc。