Iterate over Associative Arrays in Bash

Probably because many people think Bash is outdated it’s that hard to find proper resources digging into this Shell. Now we’ll have a look at an associative array and use each key to rename a file defined in value one got via wget.

Beware: Take a look at the OS X issues at the end of this article if working on a Mac!

#!/bin/bash
unset array; declare -A array # the -A attributes stands for associative
 
array[foo]=bar
array["spaced string"]="foo bar"
 
for i in ${!array[@]}
do
  # do something
done

This is how an iteration could look like. Have a look at bash-hackers.org to get more information. Thanks to Dennis Williamson solving this topic.

To get a file from the given URL perform the following command in the loop:

wget "${array[$i]}" -O "${i}.jpg"

The attribute -O renames the file.

Using variables outside Strings obviate the need for curly brackets so that $i would work as well.
Go on reading if you’re using a Mac:

Mac OS X Issues
The given example and associative arrays in bash require a Bash version greater than 4.0. OS X (Leopard) gets shipped with version 3.2.48(1). So we either have to install a newer Bash Version manually as described by Ian McCracken or use a package installer like Fink, MacPorts or Homebrew. As I am a Homebrew fanboy, here’s how to brew it:

Installing Bash > 4.0 with Homebrew

$ brew install bash # definitely gets a newer version than 4.0:
$ sudo bash -c "echo /usr/local/Cellar/bash/%INSTALLED_VERSION%/bin/bash >> /private/etc/shells" # register the new Bash as a valid Shell
$ chsh # use the new Shell for your user

In the chsh file you simply enter the path you’ve installed and registered the shell to.

You might also have to install wget because Mac OS comes without this handy tool as well:

$ brew install wget

IMPORTANT:
In your scripts you also have to define the new path of Bash! E.g:

#!/usr/local/Cellar/bash/%INSTALLED_VERSION%/bin/bash
 
some_bash_code
  1. warbirdnut says:

    Good info on bash. I bounce around between Perl and Bash. It is nice to see associated arrays in Bash. I’ll probably use it a bit more for some types of scripts Id use Perl for. You’re right bash has come along.

Leave a Reply
  1. (required)
  2. (will not be published) (required)