Skip to content

Multi array in bash

wordpress meta

title: 'Multi-Array in Bash'
date: '2014-06-02T12:34:17-05:00'
status: publish
permalink: /multi-array-in-bash
author: admin
excerpt: ''
type: post
id: 668
category:
    - Bash
tag: []
post_format: []

Well kind of... When you are used to working in Python or any real language then Bash arrays are pretty lame. But it can help in a few circumstances when you have to use Bash.

# cat bash_array.sh
#!/bin/bash
# Array pretending to be a Pythonic dictionary
ARRAY_DETAILS=( "10.51.20.63:Host1:Solaris"
                "10.51.20.80:Host2:Linux"
                "10.20.50.11:Host3:Windows" )

for hostDetails in "${ARRAY_DETAILS[@]}" ; do
  arrIN=(${hostDetails//:/ })
  IP=${arrIN[0]}
  NAME=${arrIN[1]}
  TYPE=${arrIN[2]}
  printf "Hostname %s with IP %s and is type %s.\n" "$NAME" "$IP" "$TYPE"
done

And the result looks like this:

# ./bash_array.sh
Hostname Host1 with IP 10.51.20.63 and is type Solaris.
Hostname Host2 with IP 10.51.20.80 and is type Linux.
Hostname Host3 with IP 10.20.50.11 and is type Windows.