1

I'm trying to create associative arrays based on variables. So below is a super simplified version of what I'm trying to do (the ls command is not really what I want, just used here for illustrative purposes)...

I have a statically defined array (text-a,text-b). I then want to iterate through that array, and create associative arrays with those names and _AA appended to them (so associative arrays called text-a_AA and text-b_AA).

I don't really need the _AA appended, but was thinking it might be necessary to avoid duplicate names since $NAME is already being used in the loop.

I will need those defined and will be referencing them in later parts of the script, and not just within the for loop seen below where I'm trying to define them... I want to later, for example, be able to reference text-a_AA[NUM] (again, using variables for the text-a_AA part). Clearly what I have below doesn't work... and from what I can tell, I need to be using namerefs? I've tried to get the syntax right, and just can't seem to figure it out... any help would be greatly appreciated!

#!/usr/bin/env bash
NAMES=('text-a' 'text-b')
for NAME in "${NAMES[@]}"
do
    NAME_AA="${NAME}_AA"
    $NAME_AA[NUM]=$(cat $NAME | wc -l)
done

for NAME in "${NAMES[@]}"
do
    echo "max: ${$NAME_AA[NUM]}"
done
codeforester
  • 39,467
  • 16
  • 112
  • 140
biren
  • 13
  • 4
  • What is the error? – hedgar2017 Jul 31 '17 at 22:22
  • Which version of Bash allows variable names containing `-` (as opposed to `_`)? The online [Bash](http://www.gnu.org/software/bash/manual/bash.html) manual doesn't seem to list an option, and neither Bash 3.2 nor 4.3 seems to allow it. – Jonathan Leffler Aug 01 '17 at 06:32

1 Answers1

1

You may want to use "NUM" as the name of the associative array and file name as the key. Then you can rewrite your code as:

NUM[${NAME}_AA]=$(wc -l < "$NAME")

Then rephrase your loop as:

for NAME in "${NAMES[@]}"
do
    echo "max: ${NUM[${NAME}_AA]}"
done

Check your script at shellcheck.net


As an aside: all uppercase is not a good practice for naming normal shell variables. You may want to take a look at:

codeforester
  • 39,467
  • 16
  • 112
  • 140
  • Ahhhhh brilliant! I can just flip it around! Why didn't I think of that?! haha, I will try this out, thanks! – biren Aug 01 '17 at 13:03