简体   繁体   中英

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[]?

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

Your example actually works.

echo ${array[@]}

confirms this.

You might try more efficient way of incrementing your index:

((array_counter++))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM