For integers :
(对于整数 :)
Use arithmetic expansion : $((EXPR))
(使用算术扩展 : $((EXPR))
)
num=$((num1 + num2)) num=$(($num1 + $num2)) # also works num=$((num1 + 2 + 3)) # ... num=$[num1+num2] # old, deprecated arithmetic expression syntax
Using the external expr
utility.
(使用外部expr
实用程序。)
Note that this is only needed for really old systems. (请注意,这仅适用于真正的旧系统。)
num=`expr $num1 + $num2` # whitespace for expr is important
For floating point :
(对于浮点数 :)
Bash doesn't directly support this, but there's a couple of external tools you can use:
(Bash并不直接支持这一点,但您可以使用几种外部工具:)
num=$(awk "BEGIN {print $num1+$num2; exit}")
num=$(python -c "print $num1+$num2")
num=$(perl -e "print $num1+$num2")
num=$(echo $num1 + $num2 | bc) # whitespace for echo is important
You can also use scientific notation (eg: 2.5e+2
)
(您也可以使用科学记数法(例如: 2.5e+2
))
Common pitfalls :
(常见的陷阱 :)
When setting a variable, you cannot have whitespace on either side of =
, otherwise it will force the shell to interpret the first word as the name of the application to run (eg: num=
or num
)
(设置变量时,你不能在=
两边都有空格,否则会强制shell将第一个单词解释为要运行的应用程序的名称(例如: num=
或num
))
num= 1
num =2
(
num= 1
num =2
)
bc
and expr
expect each number and operator as a separate argument, so whitespace is important.
(bc
和expr
期望每个数字和运算符作为单独的参数,因此空格很重要。)
They cannot process arguments like 3+
+4
. (他们无法处理像3+
+4
这样的论点。)
num=`expr $num1+ $num2`
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…