0

I'm trying to access data from an array while in a loop.

this command works fine..

echo "text: ${hnr1[1]}"

and this:

echo "text: ${hnr1[$loopnr]}"

However, this is giving me an headache;

echo "text: ${hnr$loopnr[1]}"

will result in:

**: text: ${hnr$loopnr[1]}: bad substitution**

Anybody knows how to solve this?

Edit: Don't get to hung up on the loop, it was a way for me to test stuff.. The data is:

array **hnr1** has **20** entries regarding **map 1**
array **hnr2** has **20** entries regarding **map 2**

so my optimal function would be:

' data=${hnr$mapnr[$field]} '
shellter
  • 36,525
  • 7
  • 83
  • 90
JoBe
  • 407
  • 2
  • 14

1 Answers1

2

Your best bet is to use an associative array instead of 66 different array variables. You can borrow a page from awk and use a delimiter that won't show up in the keys to emulate multi-dimensional arrays:

#!/usr/bin/env bash

declare -A hnr
hnr[1,0]=foo
hnr[1,1]=bar
#...
hnr[66,0]=cat
hnr[66,1]=dog
# Or all at once declare -A nhr=([1,0]=foo ... [66,1]=dog)

loopnr=66
echo "Text: ${hnr[$loopnr,1]}"

You could also use bash's indirect expansion, but the above way is going to be a lot simpler and easier to understand:

declare -a hnr66=(ball bat)
loopnr=66
# Build up the variable name - note the array index has to be part of this
varname="hnr$loopnr[1]"
# And use it.
echo "Text: ${!varname}"
Shawn
  • 47,241
  • 3
  • 26
  • 60
  • now I already have the data as: hnr1 contains 20 values regarding map1, hnr2 contains 20 values of map2 and so on.. there must be some logic way to access via ${hnr$loopnr[1]} (or something that works?) – JoBe Oct 25 '20 at 16:45
  • @JoBe You would of course rewrite the rest of your code to match using an associate array to store everything. – Shawn Oct 25 '20 at 16:47
  • I'm pretty new at arrays, but that looks pretty simple, would... echo "Text: ${hnr[$loopnr,$val]}" also work? – JoBe Oct 25 '20 at 16:55
  • 2
    @JoBe: see the 2nd half of Shawn's answer where he shows you how to use `indirect expansion` to access the values in your current arrays ... net result is it's doable but a bit convoluted; as for your 2nd comment/question re: `echo "Text ..."` ... "When in doubt, try it out!" – markp-fuso Oct 25 '20 at 17:34