Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Variable as bash array index?

Tags:

linux

bash

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

like image 240
John Hansen Avatar asked Aug 08 '12 00:08

John Hansen


People also ask

Can a variable be an 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.

Can you make an array in bash?

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.

How do you access an array in bash?

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.


1 Answers

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 
like image 95
Bob the Angry Coder Avatar answered Oct 12 '22 19:10

Bob the Angry Coder