lerom
lerom

Reputation: 1

bash: how to access a "dynamic declared variable" in a for loop

I have a problem to operate withe a "dynamic created" variable(name)

BZ="b01 b02 b03"
[user:~]$ for i in $BZ; do echo $i ; declare status_$i=foobar_"$i" ; echo wrong:  $status_$i;done

Output:

b01
wrong: b01
b02
wrong: b02
b03
wrong: b03

[user:~]$ echo $status_b01    $status_b02

Output OK:

foobar_b01 foobar_b02

The variable exists. The content ist ok. How I can get the values without to use the explicite name $status_b03? I like to use something like $status_$i (the dynamic created name of the variable).

Best Marc

Upvotes: 0

Views: 1053

Answers (1)

Poshi
Poshi

Reputation: 5762

You must use a variable with the variable name to be dereferenced:

BZ="b01 b02 b03"
for i in $BZ
do
    echo "$i"
    declare status_$i=foobar_"$i"
    vname=status_$i
    echo "${!vname}"
done

Output:

b01
foobar_b01
b02
foobar_b02
b03
foobar_b03

Upvotes: 2

Related Questions