Bash – How to Use a Variable as Part of an Array Name

bashshell

I have two arrays:

arrayA=(1 2 3)
arrayB=(a b c)

and I want to print out one of them using a command line argument, i.e., without any if else.

I tried a few variations on the syntax with no success. I am wanting to do something like this:

ARG="$1"

echo ${array${ARG}[@]}

but I get a "bad substitution" error. How can I achieve this?

Best Answer

Try doing this :

$ arrayA=(1 2 3)
$ x=A
$ var=array$x[@]
$ echo ${!var}
1 2 3

NOTE

  • from man bash (parameter expansion) :
    ${parameter}
           The value of parameter is substituted.
 The braces are required when parameter is a positional parameter with
  more than one

digit, or when parameter is followed by a character which is not to be interpreted as part of its name.
* If the first character of parameter is an exclamation point (!), a level of variable indirection is introduced. Bash uses the value of the variable formed from the rest of parameter as the name of the variable; this variable is then expanded and that value is used in the rest of the substitution, rather than the value of parameter itself. This is known as indirect expansion. * The exceptions to this are the expansions of ${!prefix*} and ${!name[@]} described below. The exclamation point must immediately follow the left brace in order to introduce indirection.

Related Question