Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

assign a random number to the variable

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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; n<5; n++, var=RANDOM%6+1)); do
   echo $var
done

The third expression makes use of the , operator, so that both n++ and var=RANDOM%6+1 are evaluated following each execution of the body of the loop.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading