In BASH, consider a (pseudo)structured list of arrays like so:
## all my arrays definitions:
myArray1=("userList1" "emailList1" "valueList1")
myArray2=("userList2" "emailList2" "valueList2")
...
myArrayN=("userListN" "emailListN" "valueListN")
## a list of the arrays I need to loop through:
active_lists=("myArray1" "myArray2" [... "myArrayN"])
I want to loop through each of the arrays I've configured in my active_lists collection.
This is often mentioned in tutorials and one would assume the following would do the trick:
for indexd in "${active_lists[@]}"; do
username=${!indexd}[0]
email=${!indexd}[1]
echo "Email: ${email}, username: ${username}"
done
Putting all this in a Bash script (with strict mode enabled) should be most straightforward:
#!/bin/bash
set -euo pipefail
declare -a myArray1=("userList1" "emailList1" "valueList1")
declare -a myArray2=("userList2" "emailList2" "valueList2")
declare -a active_lists=("myArray1" "myArray2")
for indexd in "${active_lists[@]}"; do
username=${!indexd}[2]
email=${!indexd}[1]
echo "Email: ${email}, username: ${username}"
sublist=(${!indexd})
echo "List Value: ${sublist[1]}"
done
However running the above script results in literal printing of the elements names, or unbound variable warning when attempting to access an index in the sublist:
Email: userList1[1], username: userList1[2]
Email: userList2[1], username: userList2[2]
or
line 16: sublist[1]: unbound variable
This should be simple AF and I am obviously missing something fundamental but I cannot figure out what that is, and I'm going mad! Please help.
While there may be a way to use indirect references with arrays (it's going to be a bit convoluted) I find
namerefs are much simpler to use ...With
bash 4.3+you can use anamerefto cycle through the different arrays.One
bashapproach:NOTES:
${arr_name}[$i]is not an array reference but rather 4 strings appended together (${arr_name}+[+$i+]) for display purposes${_arr[i]}is an array reference and due to thenamerefwill display theithelement of the currentarr_namearrayThis generates: