0

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.

3
  • @steeldriver sorry. This is a Linux type environment on Macbook Pro. It should be Done, not End. I have provided the full code now.
    – DS89
    Aug 23, 2022 at 20:33
  • OK I'm not sure I understand what you're trying to do here, but perhaps you want a nameref ex. declare -n tables=tables_$aschema in place of eval tables=tables_$aschema. However if the "Linux type environment" is not Ubuntu, you should ask elsewhere. Aug 23, 2022 at 20:39
  • @steeldriver thanks for your help. I have several lists. They are named as "table" followed by underscore and a suffix. For example, table_aos, table_apd, etc. I want to loop through all those lists and print the content of each list.
    – DS89
    Aug 23, 2022 at 20:45

1 Answer 1

1

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
3
  • Thank you. But it only prints the name of the table: tables_aos. It needs to print the contents of the table: A B C. I get this error message due to "declare": declare: -n: invalid option declare: usage: declare [-afFirtx] [-p] [name[=value] ...]
    – DS89
    Aug 24, 2022 at 14:39
  • @DS89 are you actually using bash version > 4.3? Check with echo "$BASH_VERSION" and/or bash --version. Are you even using Ubuntu? Aug 24, 2022 at 16:02
  • It is GNU bash, version 3.2.57(1)-release (arm64-apple-darwin21) So, that could be the issue why declare is not working as expected. Thanks for pointing that out.
    – DS89
    Aug 24, 2022 at 16:20

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .