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.
CodePudding user response:
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.
CodePudding user response:
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