[Top][All Lists]

[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
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]=  [mtu]=1500  [startmode]=auto)
eth1=([ip]=  [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).

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)

        sub this () { eval echo "\${$this[$1]:-""}" ;} <- hide indirecton in sub

        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]