Based on an associative array in a Bash script, I need to iterate over it to get the key and value.
#!/bin/bash
declare -A array
array[foo]=bar
array[bar]=foo
I actually don’t understand how to get the key while using a for-in loop.
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
The keys are accessed using an exclamation point:
${!array[@]}, the values are accessed using${array[@]}.You can iterate over the key/value pairs like this:
Note the use of quotes around the variable in the
forstatement (plus the use of@instead of*). This is necessary in case any keys include spaces.The confusion in the other answer comes from the fact that your question includes “foo” and “bar” for both the keys and the values.