What is the equivalent of Python dictionaries but in Bash (should work across OS X and Linux).
Share
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.
Bash 4
Bash 4 natively supports this feature. Make sure your script’s hashbang is
#!/usr/bin/env bashor#!/bin/bashso you don’t end up usingsh. Make sure you’re either executing your script directly, or executescriptwithbash script. (Not actually executing a Bash script with Bash does happen, and will be really confusing!)You declare an associative array by doing:
You can fill it up with elements using the normal array assignment operator. For example, if you want to have a map of
animal[sound(key)] = animal(value):Or declare and instantiate in one line:
Then use them just like normal arrays. Use
animals['key']='value'to set value"${animals[@]}"to expand the values"${!animals[@]}"(notice the!) to expand the keysDon’t forget to quote them:
Bash 3
Before bash 4, you don’t have associative arrays. Do not use
evalto emulate them. Avoidevallike the plague, because it is the plague of shell scripting. The most important reason is thatevaltreats your data as executable code (there are many other reasons too).First and foremost: Consider upgrading to bash 4. This will make the whole process much easier for you.
If there’s a reason you can’t upgrade,
declareis a far safer option. It does not evaluate data as bash code likeevaldoes, and as such does not allow arbitrary code injection quite so easily.Let’s prepare the answer by introducing the concepts:
First, indirection.
Secondly,
declare:Bring them together:
Let’s use it:
Note:
declarecannot be put in a function. Any use ofdeclareinside a bash function turns the variable it creates local to the scope of that function, meaning we can’t access or modify global arrays with it. (In bash 4 you can usedeclare -gto declare global variables – but in bash 4, you can use associative arrays in the first place, avoiding this workaround.)Summary:
declare -Afor associative arrays.declareoption if you can’t upgrade.awkinstead and avoid the issue altogether.