Using dictionaries in bash 4

:heavy_exclamation_mark: This post is older than a year. Consider some information might not be accurate anymore. :heavy_exclamation_mark:

Bash 4 supports dictionaries, hash tables or associative arrays. I was in need of that feature writing an logstash script, working with environment variables in logstash itself. A simple demonstration.

Check if bash version is 4.

tan@delta:~> bash --version
GNU bash, version 4.2.46(1)-release (x86_64-redhat-linux-gnu)
Copyright (C) 2011 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later http://gnu.org/licenses/gpl.html
This is free software; you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.

A example excerpt from my script:

# determine log environment depending on hostname
declare -A servers
servers=( ["omega"]="dev" ["delta"]="test" ["beta"]="ppd" ["alpha"]="prd" )
export LOG_ENV="${servers[$(hostname)]}"
# =====

Declare dictionary named servers

tan@delta:~> declare -A servers

Put values in dictionary

tan@delta:~> servers=( ["omega"]="dev" ["delta"]="test" ["beta"]="ppd" ["alpha"]="prd" )

Retrieve value from dictionary with key

tan@delta:~> export LOG_ENV="${servers[$(hostname)]}"
tan@delta:~> echo $LOG_ENV
Please remember the terms for blog comments.