Incorporating random integers in your Bash scripts.

There comes a time where there is a need for entropy in a script. Recently I needed to run a script on ~120 servers. I was logged in via cssh so all of my keystrokes play out on each server at the same time. I could execute the script on every server, but because the script made internal web connections, having them all execute at the same time could have been harmful as it could have flooded one of my main servers. Here is  my solution:

Bash uses a built-in variable called $RANDOM. Simply using 'echo $RANDOM' will produce an integer between zero and 32767. That isn't very useful by itself but there are ways of controlling that number. Let's look at this example:

I am doing to have the shell sleep for a random number of seconds before executing my script. This way each server will wake up and execute the script without flooding the network. But I don't want servers to potentially sleep for 32767 seconds. Instead I want to define a range of 120 seconds, or two minutes. So let's define this in a variable:

$ RANGE=120

We then need to limit the $RANDOM value with this range. so lets do this will a little bash math:

number=$RANDOM
let "number %=  $RANGE"

This limits the value of $RANDOM to the value $RANGE. If we were to script this for use later, each run will produce a random integer within that range.

$ ./rand_num 120
13
$ ./rand_num 120
21
$ ./rand_num 120
43
$ ./rand_num 120
3
$ ./rand_num 120
47
$ ./rand_num 120
48
$ ./rand_num 120
108
$ ./rand_num 120
77

So finally I could sleep for a random number of seconds and then execute my script.

Here is the script I used above:

#!/bin/bash

if [ -z "$1" ]; then
   echo "Usage: $0 <max>"
   exit 1
fi

RANGE=$1
number=$RANDOM
let "number %= $RANGE"
echo $number

Comments

Add new comment

Filtered HTML

  • Web page addresses and e-mail addresses turn into links automatically.
  • Allowed HTML tags: <a> <em> <strong> <cite> <blockquote> <code> <ul> <ol> <li> <dl> <dt> <dd>
  • Lines and paragraphs break automatically.

Plain text

  • No HTML tags allowed.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Lines and paragraphs break automatically.
CAPTCHA
This question is for testing whether you are a human visitor and to prevent automated spam submissions.
Image CAPTCHA
Enter the characters shown in the image.