Fooling around in Bash (just for fun) and discovered that you can reference an array and gets its value from the variable's name:
nick@nick-lt:~$ ARR=(one two);
nick@nick-lt:~$ ARRAYINDIRECT="ARR[@]"
nick@nick-lt:~$ echo "${!ARRAYINDIRECT}"
one two
I was interested if using the same approach we could also get the indexes of the array. Usually, I'd do that by doing:
nick@nick-lt:~$ ARR=(one two); echo "${!ARR[@]}"
0 1
but I can't find a correct syntax to do so. Here's a few ways I tried:
nick@nick-lt:~$ ARR=(one two); ARRAYINDIRECT="ARR[@]"; echo "${!!ARRAYINDIRECT}"
bash: !ARRAYINDIRECT}: event not found
ARR=(one two); ARRAYINDIRECT="!ARR[@]"; echo "${!ARRAYINDIRECT}"
bash: !ARR[@]: event not found
# Increasingly desperate attempts...
nick@nick-lt:~$ ARR=(one two); ARRAYINDIRECT="\!ARR[@]"; echo "${!ARRAYINDIRECT}"
nick@nick-lt:~$ ARR=(one two); ARRAYINDIRECT="ARR[@]"; echo "${!${!ARRAYINDIRECT}}"
bash: ${!${!ARRAYINDIRECT}}: bad substitution
nick@nick-lt:~$ ARR=(one two); ARRAYINDIRECT="ARR[@]"; echo "${\!!ARRAYINDIRECT}"
bash: !ARRAYINDIRECT}: event not found
nick@nick-lt:~$ ARR=(one two); ARRAYINDIRECT="ARR[@]"; echo "${!\!ARRAYINDIRECT}"
bash: ${!\!ARRAYINDIRECT}: bad substitution
Question: is it possible to get the array of indexes of an array after reference by name?
localvars!), so this would be great if I was iterating and mapping the elements of an array to another and I wanted to retain the index structure in the new array. In fact, it'd be great for any index-based manipulation when passed by name.