achille
achille

Reputation: 315

bash call variable built in loop

some variables are built but I don't know how to call them.

I tried:

echo "$r$z"
echo $($r$z)
echo "$($r$z)"

or

echo "$r$i"
echo $($r$i)
echo "$($r$i)"

here is the way I build the variables:

z=0;for i in {1..3};do y=$(( RANDOM % 10 ));r[z++]=$y;done

or

for i in {1..3};do eval "r$i=$(( RANDOM % 10 ))";done

the expected result should be:

r1r2r3

Upvotes: 0

Views: 55

Answers (2)

gniourf_gniourf
gniourf_gniourf

Reputation: 46823

The best is design to use arrays instead of handcooked variable names, hence Bayou's answer is what you're looking for.

Now, the way to expand variables the name of which is in another variable, exists in Bash (without using eval) and is called indirect expansion. You'll find some information about this in the Shell Parameter Expansion section of the reference manual.

In your case it will look like this:

for i in {1..3}; do
    # You need to create an auxiliary variable with the name of the variable to expand
    varname=r$i
    # Then use the indirect expansion (it's prefixed with an exclamation mark)
    echo "${!varname}"
done

This is considered poor practice and should be avoided whenever possible: the better design is to use arrays.


Just another comment about the way of creating variables without using eval is to use declare or printf. Here's how it goes with printf:

for i in {1..3}; do
    printf -v "r$i" "%d" "$((RANDOM % 10))"
done

Upvotes: 1

Bayou
Bayou

Reputation: 3441

It might be better to store them in an array instead of creating r1, r2 and r3 variables. That's because, afaik, there's not really an way to create variables from other variables.

$ r=(0);
$ z=0;
$ for i in {1..3}; do
    (( y = RANDOM % 10 ));
    r+=($y);
done
$ for i in ${r[@]}; do echo $i; done

This produces an array with three integers, in my case:

8
1
9

Upvotes: 2

Related Questions