且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在 Unix shell 脚本的变量中添加值?

更新时间:2023-12-01 09:52:40

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.