3

I am giving my first steps in bash and would like to create a associative array and iterate it. My instinct would be to do this:

declare -A FILES=(['SOURCE']='Source/Core/Core.js' ['DIST']='dist/Core.js')

for file in "${!FILES[@]}"; do
    echo $file - $FILES[$file]
done

But output is:

SOURCE - [SOURCE]
DIST - [DIST]

and no path as expected. What am I missing? and btw, is the declare -A required?

Demo: https://ideone.com/iQpjmj

Thank you

1 Answer 1

4

Place your expansions around braces. Without it, $FILES and $file would expand separately.

${FILES[$file]}

A good practice also is to place them around double quotes to prevent word splitting and possible pathname expansion:

echo "$file - ${FILES[$file]}"

Test:

$ declare -A FILES=(['SOURCE']='Source/Core/Core.js' ['DIST']='dist/Core.js')
$ for file in "${!FILES[@]}"; do echo "$file - ${FILES[$file]}"; done
SOURCE - Source/Core/Core.js
DIST - dist/Core.js
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you. One more step on my bash understanding.

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.