Linux shell number variables add All In One
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
Linux bash ${}
vs $()
\((command) is “command substitution”. \)(command) 是“命令替换”。
\({parameter} is “parameter substitution”. \){parameter} 是“参数替换”。
demos
$ animal=cat
$ cat=kitty
$ echo $animal
# cat
$ echo $cat
# kitty
# $ echo ${!animal}
# kitty ❌
# echo ${!animal} => echo ${animal=cat} ❓
$ echo ${!animal}
$ echo ${animal=cat}
# cat
$ animal=cat
# String length
$ echo ${#animal}
# 3
# Substitution, 字符串替换:c`at`/at/`ow` => cow
$ echo ${animal/at/ow}
# cow
$ echo ${animal/a/x}
# cxt
$ echo ${animal/t/y}
# cay
https://superuser.com/questions/935374/difference-between-and-in-a-shell-script
(🐞 反爬虫测试!打击盗版⚠️)如果你看到这个信息, 说明这是一篇剽窃的文章,请访问 https://www.cnblogs.com/xgqfrms/ 查看原创文章!
refs
https://github.com/xgqfrms/linux/issues/25
https://superuser.com/questions/935374/difference-between-and-in-a-shell-script
©xgqfrms 2012-2020
www.cnblogs.com/xgqfrms 发布文章使用:只允许注册用户才可以访问!
原创文章,版权所有©️xgqfrms, 禁止转载 🈲️,侵权必究⚠️!
本文首发于博客园,作者:xgqfrms,原文链接:https://www.cnblogs.com/xgqfrms/p/17009813.html
未经授权禁止转载,违者必究!