3

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? :)

1
  • note: I added the -v -d flags to debug this further, without any luck. The result without them is the same. Commented Jan 30, 2013 at 17:54

3 Answers 3

6

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..`
Sign up to request clarification or add additional context in comments.

1 Comment

and ... of course. I was so fixated on debugging the python side that I forgot about the bash side. Thanks John.
2

$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.

Comments

1

$RANDOM is a predefined variable in bash.

Open a new terminal and try it :

> echo $RANDOM
6007
> echo $RANDOM
122211

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.