如何在 Unix shell 脚本的变量中添加值?
问题描述:
我有两个变量 count1 和 count7
I have two variables called count1 and count7
count7=0
count7=$(($count7 + $count1))
这显示错误表达式不完整;需要更多令牌".
This shows an error "expression is not complete; more token required".
我应该如何添加这两个变量?
How should I add the two variables?
答
count1
设置为什么?如果未设置,则它看起来像空字符串 - 这将导致无效表达式.你用的是哪个外壳?
What is count1
set to? If it is not set, it looks like the empty string - and that would lead to an invalid expression. Which shell are you using?
在 MacOS X 10.7.1 上的 Bash 3.x 中:
In Bash 3.x on MacOS X 10.7.1:
$ count7=0
$ count7=$(($count7 + $count1))
-sh: 0 + : syntax error: operand expected (error token is " ")
$ count1=2
$ count7=$(($count7 + $count1))
$ echo $count7
2
$
如果 $count1
未设置,您也可以使用 ${count1:-0}
添加 0.
You could also use ${count1:-0}
to add 0 if $count1
is unset.