如何将 bash 脚本数组中的值加 1?

发布于 2024-12-17 03:48:39 字数 121 浏览 5 评论 0原文

我尝试使用以下代码将数组中的值增加 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

浅笑轻吟梦一曲 2024-12-24 03:48:40

试试这个

 myArr[3]=7
 (( myArr[3]++ ))
 echo ${myArr[3]}

 # output
 8

(( .... )) 可以执行 bash/ksh 的数学运算,并且内部引用的变量不需要像您的示例中那样传递出去,您可能会想类似的构造 var=$(( ... MathStuff ...)) OR var=$( ... stringStuff ... ) (注意左括号之前的“$”)。

另请注意,在 (( ... )) 内,您不需要对任何数学变量(如 $pct 或 $counter)使用前导“$”。如果您使用脚本或函数的参数,例如 $1、$2、... $N,那么您需要使用 $,因此使用 $1 的值,而不仅仅是“1”。感谢@ChrisDown 的提醒!

我希望这有帮助。

Try this

 myArr[3]=7
 (( myArr[3]++ ))
 echo ${myArr[3]}

 # output
 8

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 construct var=$(( ... 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.

梦言归人 2024-12-24 03:48:40

增量和更新:

array[1]=$((array[1]++))

Increment and update:

array[1]=$((array[1]++))
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文