How can I increment a value in a bash script array by 1?
Asked Answered
I

2

7

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]}++))
Iodism answered 19/11, 2011 at 16:48 Comment(2)
What's a unix array? Are you scripting here or something?Shellashellac
That correct - I'm writing a bash scriptIodism
V
22

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.

Vasili answered 19/11, 2011 at 17:10 Comment(4)
Not true, there are some times where you will have to refer to them with a leading $ to force the context ($1, $2 ... $N).Outherod
Great, that would certainly affect someones results. I'll update when I get back. Thanks for the improvement!Vasili
Note that the exit status will be non-zero if myArr[3] is 0 before updating.Chatter
You can also use let myArr[3]++.Chatter
A
1

Increment and update:

array[1]=$((array[1]++))
Atrocity answered 18/8, 2021 at 0:43 Comment(1)
Arithmetic expansion obviates the need to reassign the element: a=(1 2 3); ((a[0]++)); echo ${a[@]}.Medley

© 2022 - 2024 — McMap. All rights reserved.