0

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

1
  • You mean echo "${r[$z]}" ? to call them -> yea mean "to get their value"? Commented Oct 3, 2019 at 12:13

2 Answers 2

2

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

2 Comments

I've changed it to always have a 0 in the first position of the array: ${r[0]}.
I did not know this way of initialization r=(); doing r=0 gives always 3 digits, the first one beeing always 0.
1

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

1 Comment

I did know one can use ${!array[@]} to address the keys of associative arrays, but didn't realize it would work on variables as well. Cool!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.