3

I need a command line script that will generate a random integer between 1 and 6. I'm using Ubuntu with bash.
I was working on this a couple of months ago using 'bc', but never got it to work completely. I've since forgotten where I got to.

I'm using this to change a crontab script so that it will not always run every 15 minutes, but at random times (15+-3 minutes). ie. change the crontab to be every 12 minutes, and then in the script sleep for 1-6 minutes before running the script (which is basically a wget to check on the status of a webpage).

1

2 Answers 2

8

See man bash, PARAMETERS section, Shell Variables subsection:

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.

To restrict the value to the 1..6 interval use the $((RANDOM%6+1)) expression. 1

Or you can use /dev/urandom as follows:

tr -dc '1-6' < /dev/urandom | head -c 1
10
  • 1
    Definitely use /dev/urandom or /dev/random (slower) if you need more than just colloquially random numbers. Commented Jul 1, 2012 at 14:26
  • 4
    /dev/random isn't just slower, it blocks if the entropy pool is drained. Though I suspect a random number in the range 1–6 is probably going to be used for something simple. If the OP is planning on using it for encryption, the RNG period is probably the least of their problems. :)
    – Alexios
    Commented Jul 1, 2012 at 15:06
  • I'm using this to change a crontab script so that it will not always run every 15 minutes, but at random times (15+-3 minutes). Commented Jul 1, 2012 at 15:56
  • 2
    @Alexios: /dev/urandom is almost always a better choice than /dev/random. See this question and my answer. Commented Jul 1, 2012 at 20:40
  • @manatwork Your first solution does not work!!! #!/bin/bash SLPTIME=$((RANDOM%6+1))m echo $SLPTIME It always give 1m when run in a script. When I run it from the commandline it works. (Why can't I format anything in these damn comments!) Commented Jul 2, 2012 at 12:50
0

I can propose a custom linear congruential random generator or X(n+1) = (343*X(n) ) % M17 where, M17= 2^17 - 1 = 131071 is the Mersenne prime number (p=17). The pseudorandom sequence is uniformly distributed with a range [0,131070] then you can limit the range to [1,6[ as follows: Z6 = 6*X(n)/M17 + 1

Sample code:

#!/bin/bash
M=6    #change this if you need different ranges
let "z=(343*10#`date +%N`)%131071"
let "z=$M*z/131071+1"
echo $z

This is a one-shot random generator. If you need a random sequence, then the seed 10#date +%Nshall be used only once to start and the generator shall be used in a loop. Tested on Ubuntu 12.04 LTS. Have fun!

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .