#!/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[]?
An array is a variable containing multiple values. Any variable may be used as an array. There is no maximum limit to the size of an array, nor any requirement that member variables be indexed or assigned contiguously.
Any reference to a variable using a valid subscript is legal, and bash will create an array if necessary. An array variable is considered set if a subscript has been assigned a value. The null string is a valid value. It is possible to obtain the keys (indices) of an array as well as the values.
Access Array Elements Similar to other programming languages, Bash array elements can be accessed using index number starts from 0 then 1,2,3…n. This will work with the associative array which index numbers are numeric. To print all elements of an Array using @ or * instead of the specific index number.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With