Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - Bash - random numbers

Given a script 'random.sh' with the following content:

#!/bin/bash

RANDOM=`python -v -d -S -c "import random; print random.randrange(500, 800)"`
echo $RANDOM

Running this produces random numbers outside the given range:

[root@localhost nms]# ./random.sh
23031
[root@localhost nms]# ./random.sh
9276
[root@localhost nms]# ./random.sh
10996

renaming the RANDOM variable to RAND, gives me random numbers from the given range, i.e.

#!/bin/bash

RAND=`python -v -d -S -c "import random; print random.randrange(500, 800)"`
echo $RAND

gives:

[root@localhost nms]# ./random.sh
671
[root@localhost nms]# ./random.sh
683
[root@localhost nms]# ./random.sh
537

My question is -- why? :)

like image 498
Tamas Avatar asked Feb 01 '26 19:02

Tamas


2 Answers

RANDOM is a predefined bash variable. From the manpage:

RANDOM Each time this parameter is referenced, a random integer between
       0 and 32767 is generated.  The sequence of random numbers may be
       initialized by assigning a value to RANDOM.  If RANDOM is unset,
       it loses its special properties,  even  if  it  is  subsequently
       reset.

So if you really want to use the RANDOM variable name, do this:

unset RANDOM
RANDOM=`..your script..`
like image 97
isedev Avatar answered Feb 03 '26 07:02

isedev


$RANDOM is an internal bash function that returns a pseudorandom integer in the range 0-32767.

Thus in the first example you're seeing random numbers generated by bash and not by your Python script. When you assign to RANDOM, you're simply seeding bash's random number generator.

like image 33
NPE Avatar answered Feb 03 '26 08:02

NPE