Posts Tagged ‘Bash’

Iterate over Associative Arrays in Bash

Thursday, June 24th, 2010

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:
(more…)