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: Linda Walsh
Subject: Re: currently doable? Indirect notation used w/a hash
Date: Mon, 10 Jun 2013 02:43:54 -0700
User-agent: Thunderbird



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.  ;-)








reply via email to

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