bug-bash
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: currently doable? Indirect notation used w/a hash


From: Pierre Gaston
Subject: Re: currently doable? Indirect notation used w/a hash
Date: Mon, 10 Jun 2013 13:37:10 +0300

On Mon, Jun 10, 2013 at 12:43 PM, Linda Walsh <bash@tlinx.org> wrote:
>
>
> Pierre Gaston wrote:
>
>> bash4 has associative arrays:
>>
>> declare -A array
>> array[foobar]=baz
>> echo "${array[foobar]}"
>
> ---
>
> Right, and bash's namespace is also an associative array -- names & values.
>
> In the main namespace you can use '!' to introduce indirection,
> but not in a generalized way.
>
> i.e. a=foo ${!a}=1; echo $foo => '1'
>
> What I found myself wanting was having several 'sets' of
> the same parameters of info.  so I could have
> multiple hashes or associative arrays,
>
> eth0=([ip]=1.2.3.4/24  [mtu]=1500  [startmode]=auto)
> eth1=([ip]=192.168.0.1/24  [mtu]=9000 [startmode]=onboot)
>
> Then wanted to be able to pass which interface to work on, into
> a function i.e. pass in 'eth0' or 'eth1'... etc.
>
> In the function, the parameter would be in a var maybe "IF".
>
> Now I want to access the value for IP for the current "IF" (IF holding
> eth0 or eth1 or some other InterFace name).
>
> i.e.
> IF=eth0;  echo "${!IF[IP]}"
>
> but that doesn't work.  You need secondary dereferencing, like:
>
> eval echo \${$IF[IP]}
>
> I ended up using a sub, since after reading in some config files
> 99% of my usage is reading, so like:
>
> sub read_n_apply_cfg () {
>         my file="${1:?}"
>         my this="cfg_$file"
>         eval "hash -g $this"  <- creates per item hash/assoc. array
> (assigned somewhere later)
>
>         #accessor
>         sub this () { eval echo "\${$this[$1]:-""}" ;} <- hide indirecton in
> sub
>
> usage:
>         local ip=$(this ip)  #(with '$this' set at top of routine)
>
> ------
> A bit contorted, but anyone doing shell programming has to be
> used to that.  ;-)
>

Well, it's easier to ask for what you really want first.
For your use case, it seems to me that you can use the same trick that
is common for simulating arrays of arrays in awk:

declare -A ip
ip['eth0 ip']=1.2.3.4/24
ip['eth1 mtu']=1200

apply () {
  echo  "${ip["$1 ip"]}"
}
apply eth0

One drawback is that you can list the interfaces in the array with
this method, but you can use an helper array if this is needed.

eg:
declare -A ip
declare -a interfaces
addInterface () {
   interfaces+=( "$1")
   ip["$1 ip"]=$2
}

addInterface eth0 1.2.3.4/24



reply via email to

[Prev in Thread] Current Thread [Next in Thread]