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
2
  • What is the error? Commented Jul 31, 2017 at 22:22
  • Which version of Bash allows variable names containing - (as opposed to _)? The online Bash manual doesn't seem to list an option, and neither Bash 3.2 nor 4.3 seems to allow it. Commented Aug 1, 2017 at 6:32

1 Answer 1

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:

Sign up to request clarification or add additional context in comments.

1 Comment

Ahhhhh brilliant! I can just flip it around! Why didn't I think of that?! haha, I will try this out, thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.