Associative Arrays in Bash 4

by
Tags:
Category:

John Shepard, one of Chariot’s architects and newest bloggers, just recently posted this on his blog.
 A little different from our more focused software dev posts, we hope you will find this information useful.

I recently switched my work machine from OS X to Fedora. One of the first programs I noticed was missing was Time Machine. After being unable to get any of the backup software for Linux to behave as desired, a project emerged.

Ignoring most of the details of the backup scripts (all the scripts are available at the end of this post), I’m going to focus on the part working with associative arrays.

The backup program would need some way to keep only one backup per day for previous days. The obvious way to determine which days are affected is to keep a key value pair of dates and backup counts per day. Key value pairs have a few different names such as maps or dictionaries. In bash key value pairs are called associative arrays.

To declare an associative array use -A: declare -A MY_VARIABLE

To access the value just reference the variable as an array element: KEY="some value"
MY_VARIABLE["${KEY}"]

To access the value, or use zero if there is no value, use a default value
${MY_VARIABLE["${KEY}"]:-0}.

And to set a value (here the value for the key is being set to two)MY_VARIABLE["${KEY}"]=2

For looping, to access all keys ${!MY_VARIABLE[@]}. The entire set of backup scripts is available on githubcleanup_day.sh contains the associative array code.