Associative array in bash and for loop

I am taking my first steps in bash and would like to create an associative array and iterate over it. My instinct was 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 the conclusion is:

SOURCE - [SOURCE]
DIST - [DIST]

      

and there is no way as expected. What am I missing? and btw, is it required declare -A

?

Demo: https://ideone.com/iQpjmj

thank

+3


source to share


1 answer


Place your extensions around curly braces. Without it, $FILES

and $file

will be deployed separately.

${FILES[$file]}

      

It is also good practice to place them around double quotes to prevent word splitting and possible path 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

      

+3


source







All Articles