0

Normally, I may use the following expression to define a variable in bash as the number

var='3'

How could I associate the variable with the random value, e.g. from 1 to 6, which could be assigned each time in the for loop:

for var ...; do
 print $var
done

Assuming that in each iteration, the var should be randomly selected from 1 to 6.

Ken White
  • 123,280
  • 14
  • 225
  • 444

2 Answers2

2

There is no need for for loop actually, you can do it by using RANDOM. If we take your example into consideration; To create random number between 1 and 6, you can use something like;

$(( ( $RANDOM % 6 ) + 1))

You can try it with;

random_number=$(( ( $RANDOM % 6 ) + 1)); echo $random_number
Oguzhan Aygun
  • 1,314
  • 1
  • 10
  • 24
  • does it mean that randon_number would be any number in the given range in each call of the variable e.g. using echo $random_number or alternatively in each assignemnt of the variable (so it should be in FOR loop) ? – Maître Renard Mar 30 '22 at 16:22
  • `random_number` is fixed by the assignment; `RANDOM` is a special shell parameter whose value can (and usually will) change each time you access its value. – chepner Mar 30 '22 at 16:24
2

I'm not sure if your question is about generating the random number

$ echo $(( RANDOM % 6 + 1 ))
4  # results may vary

or getting a sequence of random numbers. A C-style for loop would probably be simplest.

# Roll a 6-sided dice 5 times.
for ((n=0; var=RANDOM%6+1, n<5; n++)); do
   echo $var
done

The second expression makes use of the , operator, so that both var is assigned to just before the beginning of each loop iteration.

(Or course, there's not much reason to write the loop this way. Be clear, and put the assignment at the top of the body instead.

for ((n=0; n < 5; n++)); do
    var=$((RANDOM%6 + 1))
    echo $var
done

)

chepner
  • 497,756
  • 71
  • 530
  • 681