Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamic array name in bash

Because bash doesn't support "arrays in arrays", I'm trying to dynamize variable name when calling arrays.

bash version : 4.2

I used this expansion method: https://stackoverflow.com/a/18124325/9336478

#!/bin/bash
# data are pre-defined and type is determined later

declare -a data_male
declare -a data_female

data_male=(value1 value2)
data_female=(value3 value4)

type="male" 

for value in ${${!data_$type}[@]};do
  echo $value
done

and it did not work

line 20: ${${!data_$type}[@]} : bad substitution

How do I sort this out?

like image 642
Lunartist Avatar asked Dec 07 '25 07:12

Lunartist


1 Answers

If OP can get a newer version of bash installed then a nameref (name reference, available in bash 4.3+) could be used:

declare -a data_male
declare -a data_female

data_male=(value1 value2)
data_female=(value3 value4)

type="male"

declare -n arr="data_${type}"       # dynamically declare arr[] as a name ref to data_male[]

for ndx in "${!arr[@]}"
do
    echo "${arr[${ndx}]}"
done

This generates:

value1
value2
like image 187
markp-fuso Avatar answered Dec 09 '25 00:12

markp-fuso