Associative arrays in Shell scripts

Irfan Zulfiqar picture Irfan Zulfiqar · Mar 27, 2009 · Viewed 194.5k times · Source

We required a script that simulates Associative arrays or Map like data structure for Shell Scripting, any body?

Answer

Brian Campbell picture Brian Campbell · Mar 27, 2009

Another option, if portability is not your main concern, is to use associative arrays that are built in to the shell. This should work in bash 4.0 (available now on most major distros, though not on OS X unless you install it yourself), ksh, and zsh:

declare -A newmap
newmap[name]="Irfan Zulfiqar"
newmap[designation]=SSE
newmap[company]="My Own Company"

echo ${newmap[company]}
echo ${newmap[name]}

Depending on the shell, you may need to do a typeset -A newmap instead of declare -A newmap, or in some it may not be necessary at all.