我应该使用 $(( )) 来计算 ksh 中的算术表达式吗?
1) 如果我对整数进行操作,我应该使用 $(( )) 吗?
>typeset -i x=0
>typeset -i y=0
>typeset -i z=0
>y=$(($x+1))
>print $y
1
>z=$x+1
>print $z
1
正如您所看到的,z 和 y 都有正确的结果。
仅当变量未声明为整数时才存在差异:
>typeset j
>typeset k
>j=$(($x+1))
>print $j
1
>k=$x+1
>print $k
0+1
2) $(($x+1)) 和 $((x+1)) 之间有什么区别?
打印 $(($x+1))
1
打印 $((x+1))
1
let 也有同样的情况:
x=1
让x=$x+1
打印 $x
2
令x=x+1
打印 $x
3
1) Should I use $(( )) if I operate on integers?
>typeset -i x=0
>typeset -i y=0
>typeset -i z=0
>y=$(($x+1))
>print $y
1
>z=$x+1
>print $z
1
As you can see there are correct results both in z and y.
Only in case if variable was not declared as integer there is difference:
>typeset j
>typeset k
>j=$(($x+1))
>print $j
1
>k=$x+1
>print $k
0+1
2) What is the difference between $(($x+1)) and $((x+1))?
print $(($x+1))
1
print $((x+1))
1
There is the same situation with let:
x=1
let x=$x+1
print $x
2
let x=x+1
print $x
3
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
2) 通过
$((..))
中的$x
扩展,您可以以文本方式构造表达式:显然它不适用于
$((NUM1 OP1 NUM2))
等。另一种可能性(没有
$
)可用于修改变量:对于 1),我会使用
$((..))
因为它是 POSIX,但是,我认为这在 ksh 中并不重要。2) With
$x
expansion in$((..))
, you can textually construct the expression:obviously it wouldn't work with
$((NUM1 OP1 NUM2))
etc.The other possibility (without
$
) can be used to modify the variable:For 1), I'd use
$((..))
as it is POSIX, however, I don't think it matters in ksh.与编程中的大多数事情一样,“这取决于情况”。如果您认为您的代码将在只有 bourne shell 的旧 unix 系统上使用,那么该语法将不起作用。
如果您始终处于完全现代的环境中,那么
$(( ... ))
语法确实最有意义,因为它允许简洁且类似“C 语言”的表达式。此外,正如其他人指出的那样,对于
$(( ... ))
内的任何数字变量,您可以节省键入并消除前导“$”。 ;-)如上一段所示,除了您必须少输入 1 个字符之外,没有任何区别。
最后,我赞扬你自己解决问题的方法。你的小测试帮助你自己证明了这些事实,这是一种我希望更多问题发布者能够学习使用的方法! ;-)。
您正在正确地了解如何提高您的 shell 知识。如果您不了解 shell 中可用的各种调试工具,请参阅 使用nohup执行命令很困惑?,重新
set -vx
并PS4=...
。我希望这有帮助。
As with most things in programming, "it depends". If you think your code will be used on old unix systems where there is only the bourne shell, then that syntax will not work.
If you will always be in a totally modern environment, then the
$(( ... ))
syntax really makes the most sense as it allows for concise and 'C-language' like expressions.Also, as others point out, for any numeric variables inside the
$(( ... ))
, you can save typing and eliminate the leading '$'. ;-)As indicated in the previous paragraph, there is no difference, except that you had to type 1 fewer character.
Finally, I commend you on your approach to figuring things out on your own. Your small tests helped you prove these facts for yourself and is a method I wish more question posters here on S.O would learn to use! ;-).
You are on the right track to understanding how to improve your shell knowledge. If you don't know about the various debug tools available in the shell, see the 3rd paragraph in Using nohup to execute command very confused? , r.e.
set -vx
andPS4=...
.I hope this helps.
2) $x 在 $(()) 求值之前展开:
2) $x is expanded before $(()) is evaluated: