user3078422
user3078422

Reputation: 13

Assign values to dynamic arrays

My bash script needs to read values from a properties file and assign them to a number of arrays. The number of arrays is controlled via configuration as well. My current code is as follows:

limit=$(sed '/^\#/d' $propertiesFile | grep 'limit'  | tail -n 1 | cut -d "=" -f2- | sed 's/^[[:space:]]*//;s/[[:space:]]*$//')
for (( i = 1 ; i <= $limit ; i++ ))
do
   #properties that define values to be assigned to the arrays are labeled myprop## (e.g. myprop01, myprop02):
   lookupProperty=myprop$(printf "%.2d" "$i")
   #the following line reads the value of the lookupProperty, which is a set of space-delimited strings, and assigns it to the myArray# (myArray1, myArray2, etc):
   myArray$i=($(sed '/^\#/d' $propertiesFile | grep $lookupProperty  | tail -n 1 | cut -d "=" -f2- | sed 's/^[[:space:]]*//;s/[[:space:]]*$//'))
done

When I attempt to execute the above code, the following error message is displayed:

syntax error near unexpected token `$(sed '/^\#/d' $propertiesFile | grep $lookupProperty  | tail -n 1 | cut -d "=" -f2- | sed 's/^[[:space:]]*//;s/[[:space:]]*$//')'

I am quite sure the issue is in the way I am declaring the "myArray$i" arrays. However, any different approach I tried produced either the same errors or incomplete results.

Any ideas/suggestions?

Upvotes: 1

Views: 163

Answers (1)

John1024
John1024

Reputation: 113834

You are right that bash does not recognize the construct myArray$i=(some array values) as an array variable assignment. One work-around is:

read -a myArray$i <<<"a b c"

The read -a varname command reads an array from stdin, which is provided by the "here" string <<<"a b c", and assigns it to varname where varname can be constructs like myArray$i. So, in your case, the command might look like:

read -a myArray$i <<<"$(sed '/^\#/d' $propertiesFile | grep$lookupProperty  | tail -n 1 | cut -d "=" -f2- | seds/^[[:space:]]*//;s/[[:space:]]*$//')"  

The above allows assignment. The next issue is how to read out variables like myArray$i. One solution is to name the variable indirectly like this:

var="myArray$i[2]" ; echo ${!var}

Upvotes: 2

Related Questions