Use a dictionary … in Bash!

less than 1 minute read

Originally published on: https://dev.to/ibmdeveloper/byte-sized-tech-tips-round-up-week-2-39pk

There’s already tons of literature on this topic but it’s something I learned this week.

NOTE: Bash 4.0 or newer is required for this to work.

So you want to use a dictionary in bash, why? I’m not sure, but I’ll explain how you can. Below is some code you can copy into your bash script. The most troublesome part is managing the quotation marks (").

#!/usr/bin/env bash

declare -A dict

dict=(["fruit"]="apple" ["meat"]="chicken" ["dairy"]="cheese")

for i in "${!dict[@]}"
do
    echo "$i"="${dict[$i]}"
done

Running it prints:

$ ./main.sh
dairy=cheese
fruit=apple
meat=chicken

Now you can reference key and value pairs in bash. Congrats! Now use something more sensible like Python.

Updated: