I have an array in my script that takes a list of group names. This list does not have a fixed number of elements.
GROUPS=(group1 group2 group3)
Each element in this set of GROUPS can have an unknown number of values. I dynamically create a set of arrays with a variable in the name where VARIABLE is the group name:
for VARIABLE in "${GROUPS[@]}"
do
declare -a ARRAY_${VARIABLE}
done
I want to iterate through a set of values and if a condition is met add them to the array that they belong to as new elements.
for (( VALUES=1; VALUES<=10; VALUES++ ));
do
if the VALUE belongs to GROUPx assign it to the array for GROUPx
ARRAY_$VARIABLE+=("$VALUES")
fi
done
This should end up with a set of arrays that contain values that belong the groups ie:
ARRAY_group1= 1 2 5 9 10
ARRAY_group2= 3 7
ARRAY_group3= 4 6 8
But I always get bash: syntax error near unexpected token `"$VALUES"'. If I am just assigning it to an array called ARRAY it works perfectly but I have to assign values in my script to an unknown number of arrays that need to be created dynamically.
I could instead add the values to a string whose name contains a variable with concatenation and later use sed to select individual values but I cannot find the correct syntax for this expression either.
let TEST_$VARIABLE="$TEST_$VARIABLE:$VALUES"
let TEST_$VARIABLE="${TEST_$VARIABLE}:$VALUES"
let TEST_$VARIABLE="$((TEST_$VARIABLE)):$VALUES"
let TEST_$VARIABLE="$((TEST_$VARIABLE))" ":$VALUES"
I have tried a few other things but they all run up against the exact same issue, bash really doesn't like variables being used in the variable name but I must create them dynamically which means I have to have a variable in the name.
I have tried a few other things but if you know how to refer to a variable that contains a variable in its name reliably in bash so I can avoid all of the syntax errors and bad substitution errors I would greatly appreciate it.
Tldr: Is there some syntax that I can use to get bash to treat ARRAY_$VARIABLE[@] in the same way that bash treats ARRAY[@]
perl
, a commonly used data structure called a hash-of-arrays (HoA) would be used. seeman perllol
andman perldsc
for details, but in short, you'd have a hashed array%groups
, with each element containing either a scalar (single value) or array. e.g.$groups{group1} = (1,2,5,9,10);
. The array in${groups{group1}
can be worked with and manipulated like any other array using standard functions likepush
,pop
,shift
,unshift
etc.