0

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

1 Answer 1

2

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
Sign up to request clarification or add additional context in comments.

4 Comments

perfect- thank you very much One additional (not very important question): How can I use the vname-Variables outside (after) the for-loop? What I do is do repeat the for loop-only with vname=status_$i and echo "${!vname}" do get the desired output seperated from the first for-loop. What works fine. But for example how I can compare two or more vname variables (without explicit writing $status_b01)? I like to do somthing like if [ "$status_b01" = ok ] || [ "$status_b02" = ok ]; then ....... I can use a while loop an break out after the first "not ok" but ....
It works the same way inside and outside the loop. You have the name of a variable inside another, and you dereference this variable to get the value of the other one: foo=bar; baz=foo; echo ${!baz} prints bar.
ok - but what I mean is how I can access the variables from the for-loop after the for-loop.
@lerom, you would only be able to access those variables inside the for loop. If you want to access all their output outside of the for loop, append each iteration to an array like this arr+=("${!vname}"). Then outside of the for loop you can iterate over the array like this for i in "${arr[@]}"; do echo "entry: $i"; done

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.