Python - Bash - random numbers

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

#!/bin/bash

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

      

Doing 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 variable RANDOM to RAND, gives me random numbers from a 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? :)

+3


source to share


3 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 variable name RANDOM, do this:

unset RANDOM
RANDOM=`..your script..`

      

+6


source


$RANDOM

is an internal function bash

that returns a pseudo-random integer number in the range 0-32767.



So in the first example, you are seeing random numbers generated bash

, not your Python script. When you assign RANDOM

, you are simply seeding the random number generator bash

.

+1


source


$ RANDOM is a predefined variable in bash.

Open a new terminal and try:

> echo $RANDOM
6007
> echo $RANDOM
122211

      

+1


source







All Articles