Bash: Use Associative Array: Difference between revisions
From WikiMLT
m Spas moved page Bash Use Associative Array to Bash: Use Associative Array without leaving a redirect |
m Text replacement - "mlw-continue" to "code-continue" |
||
Line 5: | Line 5: | ||
cat bash-associative-array-simple.sh | cat bash-associative-array-simple.sh | ||
</syntaxhighlight> | </syntaxhighlight> | ||
<syntaxhighlight lang="bash" line="1" class=" | <syntaxhighlight lang="bash" line="1" class="code-continue"> | ||
#!/bin/bash | #!/bin/bash | ||
Line 36: | Line 36: | ||
cat bash-associative-array-extended.sh | cat bash-associative-array-extended.sh | ||
</syntaxhighlight> | </syntaxhighlight> | ||
<syntaxhighlight lang="bash" line="1" class=" | <syntaxhighlight lang="bash" line="1" class="code-continue"> | ||
#!/bin/bash | #!/bin/bash | ||
Latest revision as of 07:30, 26 September 2022
Simple example
cat bash-associative-array-simple.sh
#!/bin/bash
declare -A content_cats
content_cats=(
["WordPress"]="This category contains..."
["MediaWiki"]="This category contains..."
["HTML and CSS"]="This category contains..."
["Linux Desktop"]="This category contains..."
["Linux Server"]="This category contains..."
)
for key in "${!content_cats[@]}"; do
echo -e "$key \t => ${content_cats[$key]}"
done
./bash-associative-array-simple.sh
MediaWiki => This category contains...
Linux Desktop => This category contains...
HTML and CSS => This category contains...
Linux Server => This category contains...
WordPress => This category contains...
Extended example
As you can see in the above example the array content is printed in wrong order. We can solve this issue by the following approach, provided by Jonathan Leffler at Stack Overflow, where is used one additional array that holds the proper order.
cat bash-associative-array-extended.sh
#!/bin/bash
declare -A content_cats
content_cats=(
["WordPress"]="This category contains..."
["MediaWiki"]="This category contains..."
["HTML and CSS"]="This category contains..."
["Linux Desktop"]="This category contains..."
["Linux Server"]="This category contains..."
)
declare -a content_cats_order
content_cats_order=(
"WordPress"
"MediaWiki"
"HTML and CSS"
"Linux Desktop"
"Linux Server"
)
for key in "${content_cats_order[@]}"
do
echo -e "$key \t => ${content_cats[$key]}"
done
./bash-associative-array-extended.sh
WordPress => This category contains...
MediaWiki => This category contains...
HTML and CSS => This category contains...
Linux Desktop => This category contains...
Linux Server => This category contains...
Reference manual
References
- Stack Overflow: How to keep associative array order?
- Stack Overflow: What does declare ‑A do in Linux shell?
- Viet Nguyen Tien: How to use arrays in Bash