Linux shell number variables add All In One
bash / zsh
error ❌
# string number / 字符串数字
$ var1=1
$ var2=2
$ echo $var1
# 1
$ echo $var2
# 2
$ echo $var1$var2
# 12
$ echo $var1 + $var2
# 1 + 2
$ echo ${var1 + var2}
# zsh: bad substitution ❌
$ echo ${var1} + ${var2}
# 1 + 2
solutions ✅
declare -i
$ var1=1
$ echo $var1
# 1
$ var1+=1
$ echo $var1
# 11
# 声明为 integer 整数类型 ✅ `declare -i`
$ declare -i num1
$ num1=1
$ echo $num1
# 1
$ num1+=1
$ echo $num1
# 2
- Use
$(())
for basharithmetic expansion
.
使用 $(()) 进行 bash 算术扩展。
$ var1=1
$ var2=2
$ echo $var1 + $var2
# 1 + 2
$ echo $(($var1 + $var2))
# 3
https://infoheap.com/bash-add-number-variable/
-
??? 逆波兰表达式
-
let
# let
https://stackoverflow.com/questions/6348902/how-can-i-add-numbers-in-a-bash-script
https://linux.die.net/man/1/dc
https://www.computerhope.com/unix/bash/let.htm