Jun 02

Multi-Array in Bash

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.

Comments Off on Multi-Array in Bash
comments

Reply