0

I am writing a bash script where I need to create arrays inside a for loop and name each array using the string contained in the counter (an array element) each iteration.

Here is the code:

myArray=( joe bob dave mark )


for i in "${myArray[@]}"
do
  "$k_array"=( `cat fileUsedToPopulate.txt` )
done

# echo to test if one of the arrays has been created and populated

for j in "${joe_array[@]}"
do
  echo $j
done

The desired result is 4 arrays, joe_array bob_array etc, each populated with the file.

However I haven't found anyway to escape the $k so that it appends to the array name when declaring/populating it.

Here is the error I am getting:

line 30: syntax error near unexpected token `cat fileUsedToPopulate.txt' line 30: "$k_array"=(cat $DIR/$braDir/oem.txt` )'

Thanks for any help provided.

1 Answer 1

2

Use eval to assign to variable whose name depends on another variable:

val=$(cat fileUsedToPopulate.txt)
for k in "${myArray[@]}"
do
  eval "${k}_array"="\"${val}\""
done

Note that you need nested double quotes (with proper escaping) if the contents of the file contain a space or other separator. Otherwise shell is going to interpret part of it as a command to execute. Also, you need braces around variable name in $k or the shell will look for a variable names k_array.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you for your reply. A note on the file used, this is example code, in my actual script the file used to populate the arrays is different for each iteration. There is a path used to point towards the text file that also depends on $k. I tried to use the eval code, however it doesn't escape the first \ and the loop doesn't terminate properly.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.