32
#!/bin/bash

set -x

array_counter=0
array_value=1

array=(0 0 0)

for number in ${array[@]}
do
    array[$array_counter]="$array_value"
    array_counter=$(($array_counter + 1))
done

When running above script I get the following debug output:

+ array_counter=0
+ array_value=1
+ array=(0 0 0)
+ for number in '${array[@]}'
+ array[$array_counter]=1
+ array_counter=1
+ for number in '${array[@]}'
+ array[$array_counter]=1
+ array_counter=2
+ for number in '${array[@]}'
+ array[$array_counter]=1
+ array_counter=3

Why does the variable $array_counter not expand when used as index in array[]?

3
  • What's it not doing that you expect? After your loop, array is "1 1 1" Commented Aug 8, 2012 at 0:51
  • I would expect the debug output to show array[0]=1, array[1]=1 and so on. Commented Aug 8, 2012 at 0:57
  • ah, you're just worried about the debug output. I'm actually surprised it works at all without an eval, but it could be that lhs arrays are expanded differently. Commented Aug 8, 2012 at 1:12

2 Answers 2

35

Bash seems perfectly happy with variables as array indexes:

$ array=(a b c)
$ arrayindex=2
$ echo ${array[$arrayindex]}
c
$ array[$arrayindex]=MONKEY
$ echo ${array[$arrayindex]}
MONKEY
Sign up to request clarification or add additional context in comments.

1 Comment

...and since array indices get evaluated in an arithmetic context you don't even need $, you can even do things like ${array[arrayindex-1]} which validly refers to b.
-2

Your example actually works.

echo ${array[@]}

confirms this.

You might try more efficient way of incrementing your index:

((array_counter++))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.