My script has a bunch of changing variables that start with the string "versions_" so for example:
versions_a=("1" "2")
versions_b=("3" "4")
I want to loop through these variables and access the underlying arrays:
#!/usr/bin/env bash
versions_a=("1" "2")
versions_b=("3" "4")
for i in ${!versions_*}; do
#Ideally if statement here if underlying array is empty, continue to next iteration
echo "${i} contains ${i[*]}"
versions=(${!i})
echo "versions has ${versions[@]}"
for x in "${versions[@]}"; do
echo ${x} #should print 1, then 2, then 3, then 4
done
done
Expected output:
versions_a has 1 2
versions has 1 2
1
2
versions_b has 3 4
versions has 3 4
3
4
Current output:
versions_a contains versions_a
versions has 1
1
versions_b contains versions_b
versions has 3
3
line 6: ${versions_*}: bad substitution
– Hauke Laging May 19 '23 at 18:18for i in a b c d;...
to know which array to look at? Or perhaps you want to use associative instead of indexed arrays? – terdon May 19 '23 at 18:54versions_
. – CeePlusPlus May 19 '23 at 19:03echo "${i} contains ${i[*]}"
, it's because scalars and ksh-style arrays are somewhat interchangeable.$i
is the same${i[0]}
, and similarly${i[*]}
just joins the single element of the "array" to a string.for i in ...
only fills the element at index0
. – ilkkachu May 19 '23 at 20:15