Bash – Referencing bash array variables from another array

bashshell-script

I want to write a script to reference multiple arrays from another array which holds these array's variable names.

Here's my code so far:

#!/bin/bash
array1=('array1string1' 'array1string2')
array2=('array2string1' 'array2string2')

array_names=('array1' 'array2')

for a in ${array_names[@]}
do
        for b in ${a[@]}
        do
                echo $b
        done
done

I'd like the output to scan through both arrays (from the outer for loop) and print the respective strings in the inner for loop which calls echo. My current output is just showing me:

array1
array2

I'd be grateful for any pointers regarding this. Thank you!

Best Answer

Bash 4.3 and later supports "name references", or namerefs (a similar concept exists in ksh93, but the scoping is annoyingly different):

#!/bin/bash

array1=('array1string1' 'array1string2')
array2=('array2string1' 'array2string2')

array_names=('array1' 'array2')

for a in "${array_names[@]}"; do
    declare -n arr="$a"

    for b in "${arr[@]}"; do
        echo "$b"
    done
done

The variable arr is a nameref that acts like an alias for the named variable (the variable with name $a in this example).

Without namerefs, in earlier Bash versions, one solution would be to create a new array that contains all the elements from the other arrays:

all=( "${array1[@]}" "${array2[@]}" )

... a bit like the array_names array in the question but with the contents of all arrays, and then iterate over "${all[@]}".

It's also possible to use eval, but the resulting code looks astoundingly awful.

See glenn jackman's answer for a variation with variable indirection (introduced in its current form with Bash version 2).

Related Question