command-line – Fix String Evaluation Not Working in Bash Scripts

bashcommand linescripts

I have the following array in a shell script:

#! usr/bin/bash

schemaPrefix=("aos")
tables_aos=("A" "B" "C")
colnames_aos=("id" "id" "id")

for j in "${!schemaPrefix[@]}"; do

aschema=${schemaPrefix[j]}
schema=$aschema
eval tables=tables_$aschema
echo ${tables[@]}
done

This code should display:

A B C

However, it displays:

tables_aos

What am I doing wrong? Thanks.

Best Answer

In bash version > 4.3, you can declare the tables variable as a nameref:

#! /usr/bin/bash

schemaPrefix=("aos")
tables_aos=("A" "B" "C")

declare -n tables

for j in "${!schemaPrefix[@]}"; do
  aschema=${schemaPrefix[j]}
  tables=tables_$aschema
  echo "${tables[@]}"
done

The loop could be written more simply without indirection as

for aschema in "${schemaPrefix[@]}"; do
  tables=tables_$aschema
  echo "${tables[@]}"
done