Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. It's 100% free, no registration required.

I want to define a hash list in bash (version 4.3.30):

  • 4 gateways
  • each gateway has
    • an IP
    • an IP6
    • a name
    • ...

and I want to walk through this list in a loop and do stuff to each gateway.

I searched a lot, but it seems, bash doesn't support multidimensional arrays?

share|improve this question

1 Answer 1

up vote 8 down vote accepted

bash doesn't have multi-dimensional arrays yet. Only ksh93 does.

Here, you can use a csv-like structure and you don't even need to use arrays:

#! /bin/sh -
gws="\
foo,1.1.1.12,1::1
blah,2.2.2.2,2::2"

while IFS=, read name ip4 ip6; do
  echo something with "$name" "$ip4"...
done << E
$gws
E

(you don't even need bash)

With ksh93:

gws=(
  (name=foo  ip4=1.1.1.1 ip6=1::1)
  (name=blah ip4=2.2.2.2 ip6=1::2)
)

printf '%s\n' "${gws[0].name}"
share|improve this answer
    
Can you fill in the << E $gws E in the beginning somehow? –  rubo77 Jul 23 at 9:42
    
@rubo77, no, but you could use a function if you want to make it neater. –  Stéphane Chazelas Jul 23 at 9:46
    
@rubo77, I just meant process_gws() while...; done; process_gws <<... which you may find neater. That's all cosmetic considerations. –  Stéphane Chazelas Jul 23 at 10:14
    
It should work fine as is. Bash lets you use <<< "$gws" to redirect from a string, instead of needing a multi-line here-document. But either construct should work in a function. –  Peter Cordes Jul 23 at 10:16
    
@rubo77, in that case, the while loop runs in a subshell. –  Stéphane Chazelas Jul 23 at 11:02

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.