Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Variable substitution in an array

Status
Not open for further replies.

avalon111

IS-IT--Management
Feb 11, 2010
10
NL
Hi!

I want to quote an array named with a string that includes a pre-defined variable name.

Here's what I mean.

I have a variable that can have two value strings; PR and ET.

So set to PR



I have a text file with values set with the following;

PR_eth_virtual_adapters_lan_id 151 152 151 251 252 251
ET_eth_virtual_adapters_lan_id 351 352 351 451 452 451

If I set ROLE to PR;

ROLE=PR

And then set the array and its values with this;

set -A `grep -E "${ROLE_eth_virtual_adapters_lan_id" ./<text file> | cut -d " " -f 1 ; grep -E
"${ROLE}_eth_virtual_adapters_lan_id" ./<text file> | cut -d " " -f 2-`

that works fine (and should do)

But retrieving the values is harder;

This works fine;

echo ${PR_eth_virtual_adapters_lan_id[*]}

But what I want to do is this;

echo ${ROLE_eth_virtual_adapters_lan_id[*]}

and this doesn't work, or indeed any combination I've tried which embeds the variable name ROLE in the array name.

Any help would be gratefully received!

remshell



 
[tt]set -A `grep -E "${ROLE_eth_virtual_adapters_lan_id" ./<text file> | cut -d " " -f 1 ; grep -E "${ROLE}_eth_virtual_adapters_lan_id" ./<text file> | cut -d " " -f 2-`[/tt]

that works fine (and should do) [red] no it doesn't![/red]

[tt]set -A `grep -E "${ROLE[red]}[/red]_eth_virtual_adapters_lan_id" ./<text file> | cut -d " " -f 1 ; grep -E "${ROLE}_eth_virtual_adapters_lan_id" ./<text file> | cut -d " " -f 2-`[/tt]

As to your question: you need eval for that, but it's not something I would use...

[tt]echo "$(eval echo \$\{${ROLE}_eth_virtual_adapters_lan_id\[\*\]\})"[/tt]



HTH,

p5wizard
 
Finally figured-out a soolution with the assistance of a colleague;

eval echo \${${ROLE}_eth_virtual_adapters_lan_id[*]}
 
Sorry p5wizard, posted without refreshing.

Your solution works too, but so too does the eval without quite so many escapes.

This saves a lot of lines in my script, not having to evaluate ROLE and set arrays accordingly for either PR or ET values. Plus I have an iteration to set arrays without even referring to them by name in the script.
 
No worries, just make sure you document your [tt]eval[/tt] usage for whoever comes after you... ;-)


HTH,

p5wizard
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top