如何将 bash 脚本数组中的值加 1?
我尝试使用以下代码将数组中的值增加 1,但是我遇到了一些问题。请问有人可以帮我吗?
myArray[$position]=((${myArray[$position]}++))
I'm trying to increment a value in an array by 1 using the following code, however I'm having some problems with it. Please can someone help me out?
myArray[$position]=((${myArray[$position]}++))
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
试试这个
(( .... ))
可以执行 bash/ksh 的数学运算,并且内部引用的变量不需要像您的示例中那样传递出去,您可能会想类似的构造var=$(( ... MathStuff ...)) OR var=$( ... stringStuff ... )
(注意左括号之前的“$”)。另请注意,在
(( ... ))
内,您不需要对任何数学变量(如 $pct 或 $counter)使用前导“$”。如果您使用脚本或函数的参数,例如 $1、$2、... $N,那么您需要使用 $,因此使用 $1 的值,而不仅仅是“1”。感谢@ChrisDown 的提醒!我希望这有帮助。
Try this
The
(( .... ))
can perform bash/ksh's math operations, and the variables referenced inside, don't need to be passed out as in your example, you're probably thinking of a similar constructvar=$(( ... MathStuff ...)) OR var=$( ... stringStuff ... )
(note the '$' before the opening paren).Also note that inside
(( ... ))
you don't need to use the leading '$' for any math variables like $pct or $counter. If you're using arguments to the script or a function like $1, $2, ... $N, THEN you need to use the $, so the value of $1 is used, instead of just '1'. Thanks to @ChrisDown for the reminder!I hope this helps.
增量和更新:
Increment and update: