mat297
mat297

Reputation: 3

In Bash, get name of array being looped through when looping through multiple arrays?

I have two arrays of different length, and am passing both arrays into a while loop. Within the while loop, I need access to the name of the array. I can write this as a function, but am curious if there is a way to do it without.

arr1=( "a" "b" "c" )
arr2=( "d" "e" "f" "g" )
for str in ${arr1[@]} ${arr2[@]}; do
  echo $str
  echo ${NAME_OF_ARRAY}
done

with the expected result:

a
arr1
b
arr1
c
arr1
d
arr2
e
arr2
f
arr2
g
arr2

Is there a way of extracting the name of the array like this from within a for loop?

Upvotes: 0

Views: 23

Answers (1)

Charles Duffy
Charles Duffy

Reputation: 295403

No, you can't do that. Instead, with bash 4.3 or newer, loop over the array names, using a namevar to alias each in turn.

arr1=( "a" "b" "c" )
arr2=( "d" "e" "f" "g" )

for arr_name in arr1 arr2; do      # assign each array name to arr_name in turn
  declare -n arr_cur=$arr_name     # make arr_cur an alias for arr_name
  for str in "${arr_cur[@]}"; do   # iterate over "${arr_cur[@]}"
     echo "${arr_name} - ${str}"
  done
  unset -n arr_cur                 # revert that assignment
done

...properly emits:

arr1 - a
arr1 - b
arr1 - c
arr2 - d
arr2 - e
arr2 - f
arr2 - g

Upvotes: 2

Related Questions