0

Before we get into the question, I know there are answers SIMILAR to this on stack overflow already. However this one is unique in it's use of the eval statement with associative arrays. ( Believe me I've read them all ).

Okay now into the question

I have X number of arrays defined via an eval function similar to this:

for (( i=1;i<=X;i++ ))
do
   eval "declare -gA old$i"
   eval "old$i[key]=value"
done

This code is in function : makeArrays

Now I have a second function that must loop through these different arrays

old1
old2
.
.
.
oldX

I'll call this function : useArrays

Now, I have a for loop for this useArrays function.

for (( i=0;i<$#;i++ ))
do
  // ACCESS OLD1[KEY]
done

My question is, how do I access this array FOR COMPARISONS. I.E. if[ old1 -eq 0 ] then ... fi

Is there a way I could COPY these associate arrays into a variable I can use for comparisons using eval as little as possible?

Andrew Costanzo
  • 97
  • 1
  • 1
  • 6

1 Answers1

3

Modern versions of bash support namerefs (originally a ksh feature), so you can point a constant name at any variable you choose; this makes eval unnecessary for the purposes to which you're presently placing it.

key="the key you want to test"
for (( i=0;i<$#;i++ )); do
  declare -n "oldArray=old$i"  # map the name oldArray to old0/old1/old2/...
  printf 'The value of %q in old%q is: %q\n' "$key" "$i" "${oldArray[$key]}"
  unset -n "oldArray"          # remove that mapping
done

You could of course refer to "${!oldArray[@]}" to iterate over its keys; also map a newArray namevar to compare with; etc.

Charles Duffy
  • 280,126
  • 43
  • 390
  • 441
  • So for each key of my associative array I need to run a for loop. It seems super inefficient. – Andrew Costanzo Jun 22 '20 at 15:11
  • Could you explain the other two options in more detail? I've read stack overflow answers that mention what you explain here, but does not seem feasible for my situation. Especially because the old arrays were given unique numbers. – Andrew Costanzo Jun 22 '20 at 15:12
  • The question referred to `key` but didn't take it from anywhere. Thus, I assumed you only wanted to compare one key. – Charles Duffy Jun 22 '20 at 16:13
  • 2
    ...honestly, if you want to compare the whole associative array, I'd just use `declare -p` to convert the whole thing to a string and remove the front). Still no `eval` needed. – Charles Duffy Jun 22 '20 at 16:13