John Hansen
John Hansen

Reputation: 321

Variable as bash array index?

#!/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[]?

Upvotes: 32

Views: 52924

Answers (2)

user2038893
user2038893

Reputation: 344

Your example actually works.

echo ${array[@]}

confirms this.

You might try more efficient way of incrementing your index:

((array_counter++))

Upvotes: -2

Bob the Angry Coder
Bob the Angry Coder

Reputation: 1344

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

Upvotes: 35

Related Questions