9.6. $RANDOM: generate random integer

$RANDOM is an internal Bash function (not a constant) that returns a pseudorandom integer in the range 0 - 32767. $RANDOM should not be used to generate an encryption key.


Example 9-23. Generating random numbers

   1 #!/bin/bash
   2 
   3 # $RANDOM returns a different random integer at each invocation.
   4 # Nominal range: 0 - 32767 (signed 16-bit integer).
   5 
   6 MAXCOUNT=10
   7 count=1
   8 
   9 echo
  10 echo "$MAXCOUNT random numbers:"
  11 echo "-----------------"
  12 while [ "$count" -le $MAXCOUNT ]      # Generate 10 ($MAXCOUNT) random integers.
  13 do
  14   number=$RANDOM
  15   echo $number
  16   let "count += 1"  # Increment count.
  17 done
  18 echo "-----------------"
  19 
  20 # If you need a random int within a certain range, use the 'modulo' operator.
  21 # This returns the remainder of a division operation.
  22 
  23 RANGE=500
  24 
  25 echo
  26 
  27 number=$RANDOM
  28 let "number %= $RANGE"
  29 echo "Random number less than $RANGE  ---  $number"
  30 
  31 echo
  32 
  33 # If you need a random int greater than a lower bound,
  34 # then set up a test to discard all numbers below that.
  35 
  36 FLOOR=200
  37 
  38 number=0   #initialize
  39 while [ "$number" -le $FLOOR ]
  40 do
  41   number=$RANDOM
  42 done
  43 echo "Random number greater than $FLOOR ---  $number"
  44 echo
  45 
  46 
  47 # May combine above two techniques to retrieve random number between two limits.
  48 number=0   #initialize
  49 while [ "$number" -le $FLOOR ]
  50 do
  51   number=$RANDOM
  52   let "number %= $RANGE"  # Scales $number down within $RANGE.
  53 done
  54 echo "Random number between $FLOOR and $RANGE ---  $number"
  55 echo
  56 
  57 
  58 # Generate binary choice, that is, "true" or "false" value.
  59 BINARY=2
  60 number=$RANDOM
  61 T=1
  62 
  63 let "number %= $BINARY"
  64 #  Note that    let "number >>= 14"    gives a better random distribution
  65 #+ (right shifts out everything except last binary digit).
  66 if [ "$number" -eq $T ]
  67 then
  68   echo "TRUE"
  69 else
  70   echo "FALSE"
  71 fi  
  72 
  73 echo
  74 
  75 
  76 # Generate toss of the dice.
  77 SPOTS=6   # Modulo 6 gives range 0 - 5.
  78           # Incrementing by 1 gives desired range of 1 - 6.
  79           # Thanks, Paulo Marcel Coelho Aragao, for the simplification.
  80 die1=0
  81 die2=0
  82 
  83 # Tosses each die separately, and so gives correct odds.
  84 
  85     let "die1 = $RANDOM % $SPOTS +1" # Roll first one.
  86     let "die2 = $RANDOM % $SPOTS +1" # Roll second one.
  87 
  88 let "throw = $die1 + $die2"
  89 echo "Throw of the dice = $throw"
  90 echo
  91 
  92 
  93 exit 0


Example 9-24. Picking a random card from a deck

   1 #!/bin/bash
   2 # pick-card.sh
   3 
   4 # This is an example of choosing a random element of an array.
   5 
   6 
   7 # Pick a card, any card.
   8 
   9 Suites="Clubs
  10 Diamonds
  11 Hearts
  12 Spades"
  13 
  14 Denominations="2
  15 3
  16 4
  17 5
  18 6
  19 7
  20 8
  21 9
  22 10
  23 Jack
  24 Queen
  25 King
  26 Ace"
  27 
  28 suite=($Suites)                # Read into array variable.
  29 denomination=($Denominations)
  30 
  31 num_suites=${#suite[*]}        # Count how many elements.
  32 num_denominations=${#denomination[*]}
  33 
  34 echo -n "${denomination[$((RANDOM%num_denominations))]} of "
  35 echo ${suite[$((RANDOM%num_suites))]}
  36 
  37 
  38 # $bozo sh pick-cards.sh
  39 # Jack of Clubs
  40 
  41 
  42 # Thank you, "jipe," for pointing out this use of $RANDOM.
  43 exit 0

Jipe points out a set of techniques for generating random numbers within a range.
   1 #  Generate random number between 6 and 30.
   2 rnumber=$((RANDOM%25+6))	
   3 
   4 #  Generate random number in the same 6 - 30 range,
   5 #+ but the number must be evenly divisible by 3.
   6 rnumber=$(((RANDOM%30/3+1)*3))
   7 
   8 # Note that this will not work all the time.
   9 # It fails if $RANDOM returns 0.
  10 
  11 #  Exercise: Try to figure out the pattern here.

Bill Gradwohl came up with an improved formula that works for positive numbers.
   1 rnumber=$(((RANDOM%(max-min+divisibleBy))/divisibleBy*divisibleBy+min))

Here Bill presents a versatile function that returns a random number between two specified values.


Example 9-25. Random between values

   1 #!/bin/bash
   2 # random-between.sh
   3 # Random number between two specified values. 
   4 # Script by Bill Gradwohl, with minor modifications by the document author.
   5 # Used with permission.
   6 
   7 
   8 randomBetween() {
   9    #  Generates a positive or negative random number
  10    #+ between $min and $max
  11    #+ and divisible by $divisibleBy.
  12    #  Gives a "reasonably random" distribution of return values.
  13    #
  14    #  Bill Gradwohl - Oct 1, 2003
  15 
  16    syntax() {
  17    # Function embedded within function.
  18       echo
  19       echo    "Syntax: randomBetween [min] [max] [multiple]"
  20       echo
  21       echo    "Expects up to 3 passed parameters, but all are completely optional."
  22       echo    "min is the minimum value"
  23       echo    "max is the maximum value"
  24       echo    "multiple specifies that the answer must be a multiple of this value."
  25       echo    "    i.e. answer must be evenly divisible by this number."
  26       echo    
  27       echo    "If any value is missing, defaults area supplied as: 0 32767 1"
  28       echo    "Successful completion returns 0, unsuccessful completion returns"
  29       echo    "function syntax and 1."
  30       echo    "The answer is returned in the global variable randomBetweenAnswer"
  31       echo    "Negative values for any passed parameter are handled correctly."
  32    }
  33 
  34    local min=${1:-0}
  35    local max=${2:-32767}
  36    local divisibleBy=${3:-1}
  37    # Default values assigned, in case parameters not passed to function.
  38 
  39    local x
  40    local spread
  41 
  42    # Let's make sure the divisibleBy value is positive.
  43    [ ${divisibleBy} -lt 0 ] && divisibleBy=$((0-divisibleBy))
  44 
  45    # Sanity check.
  46    if [ $# -gt 3 -o ${divisibleBy} -eq 0 -o  ${min} -eq ${max} ]; then 
  47       syntax
  48       return 1
  49    fi
  50 
  51    # See if the min and max are reversed.
  52    if [ ${min} -gt ${max} ]; then
  53       # Swap them.
  54       x=${min}
  55       min=${max}
  56       max=${x}
  57    fi
  58 
  59    #  If min is itself not evenly divisible by $divisibleBy,
  60    #+ then fix the min to be within range.
  61    if [ $((min/divisibleBy*divisibleBy)) -ne ${min} ]; then 
  62       if [ ${min} -lt 0 ]; then
  63          min=$((min/divisibleBy*divisibleBy))
  64       else
  65          min=$((((min/divisibleBy)+1)*divisibleBy))
  66       fi
  67    fi
  68 
  69    #  If max is itself not evenly divisible by $divisibleBy,
  70    #+ then fix the max to be within range.
  71    if [ $((max/divisibleBy*divisibleBy)) -ne ${max} ]; then 
  72       if [ ${max} -lt 0 ]; then
  73          max=$((((max/divisibleBy)-1)*divisibleBy))
  74       else
  75          max=$((max/divisibleBy*divisibleBy))
  76       fi
  77    fi
  78 
  79    #  ---------------------------------------------------------------------
  80    #  Now do the real work.
  81 
  82    #  Note that to get a proper distribution for the end points, the
  83    #+ range of random values has to be allowed to go between 0 and
  84    #+ abs(max-min)+divisibleBy, not just abs(max-min)+1.
  85 
  86    #  The slight increase will produce the proper distribution for the
  87    #+ end points.
  88 
  89    #  Changing the formula to use abs(max-min)+1 will still produce
  90    #+ correct answers, but the randomness of those answers is faulty in
  91    #+ that the number of times the end points ($min and $max) are returned
  92    #+ is considerably lower than when the correct formula is used.
  93    #  ---------------------------------------------------------------------
  94 
  95    spread=$((max-min))
  96    [ ${spread} -lt 0 ] && spread=$((0-spread))
  97    let spread+=divisibleBy
  98    randomBetweenAnswer=$(((RANDOM%spread)/divisibleBy*divisibleBy+min))   
  99 
 100    return 0
 101 
 102    #  However, Paulo Marcel Coelho Aragao points out that
 103    #+ when $max and $min are not divisible by $divisibleBy,
 104    #+ the formula fails.
 105    #
 106    #  He suggests instead the following formula:
 107    #    rnumber = $(((RANDOM%(max-min+1)+min)/divisibleBy*divisibleBy))
 108 
 109 }
 110 
 111 # Let's test the function.
 112 min=-14
 113 max=20
 114 divisibleBy=3
 115 
 116 
 117 #  Generate an array of expected answers and check to make sure we get
 118 #+ at least one of each answer if we loop long enough.
 119 
 120 declare -a answer
 121 minimum=${min}
 122 maximum=${max}
 123    if [ $((minimum/divisibleBy*divisibleBy)) -ne ${minimum} ]; then 
 124       if [ ${minimum} -lt 0 ]; then
 125          minimum=$((minimum/divisibleBy*divisibleBy))
 126       else
 127          minimum=$((((minimum/divisibleBy)+1)*divisibleBy))
 128       fi
 129    fi
 130 
 131 
 132    #  If max is itself not evenly divisible by $divisibleBy,
 133    #+ then fix the max to be within range.
 134 
 135    if [ $((maximum/divisibleBy*divisibleBy)) -ne ${maximum} ]; then 
 136       if [ ${maximum} -lt 0 ]; then
 137          maximum=$((((maximum/divisibleBy)-1)*divisibleBy))
 138       else
 139          maximum=$((maximum/divisibleBy*divisibleBy))
 140       fi
 141    fi
 142 
 143 
 144 #  We need to generate only positive array subscripts,
 145 #+ so we need a displacement that that will guarantee
 146 #+ positive results.
 147 
 148 displacement=$((0-minimum))
 149 for ((i=${minimum}; i<=${maximum}; i+=divisibleBy)); do
 150    answer[i+displacement]=0
 151 done
 152 
 153 
 154 # Now loop a large number of times to see what we get.
 155 loopIt=1000   #  The script author suggests 100000,
 156               #+ but that takes a good long while.
 157 
 158 for ((i=0; i<${loopIt}; ++i)); do
 159 
 160    #  Note that we are specifying min and max in reversed order here to
 161    #+ make the function correct for this case.
 162 
 163    randomBetween ${max} ${min} ${divisibleBy}
 164 
 165    # Report an error if an answer is unexpected.
 166    [ ${randomBetweenAnswer} -lt ${min} -o ${randomBetweenAnswer} -gt ${max} ] && echo MIN or MAX error - ${randomBetweenAnswer}!
 167    [ $((randomBetweenAnswer%${divisibleBy})) -ne 0 ] && echo DIVISIBLE BY error - ${randomBetweenAnswer}!
 168 
 169    # Store the answer away statistically.
 170    answer[randomBetweenAnswer+displacement]=$((answer[randomBetweenAnswer+displacement]+1))
 171 done
 172 
 173 
 174 
 175 # Let's check the results
 176 
 177 for ((i=${minimum}; i<=${maximum}; i+=divisibleBy)); do
 178    [ ${answer[i+displacement]} -eq 0 ] && echo "We never got an answer of $i." || echo "${i} occurred ${answer[i+displacement]} times."
 179 done
 180 
 181 
 182 exit 0

Just how random is $RANDOM? The best way to test this is to write a script that tracks the distribution of "random" numbers generated by $RANDOM. Let's roll a $RANDOM die a few times...


Example 9-26. Rolling a single die with RANDOM

   1 #!/bin/bash
   2 # How random is RANDOM?
   3 
   4 RANDOM=$$       # Reseed the random number generator using script process ID.
   5 
   6 PIPS=6          # A die has 6 pips.
   7 MAXTHROWS=600   # Increase this, if you have nothing better to do with your time.
   8 throw=0         # Throw count.
   9 
  10 ones=0          #  Must initialize counts to zero,
  11 twos=0          #+ since an uninitialized variable is null, not zero.
  12 threes=0
  13 fours=0
  14 fives=0
  15 sixes=0
  16 
  17 print_result ()
  18 {
  19 echo
  20 echo "ones =   $ones"
  21 echo "twos =   $twos"
  22 echo "threes = $threes"
  23 echo "fours =  $fours"
  24 echo "fives =  $fives"
  25 echo "sixes =  $sixes"
  26 echo
  27 }
  28 
  29 update_count()
  30 {
  31 case "$1" in
  32   0) let "ones += 1";;   # Since die has no "zero", this corresponds to 1.
  33   1) let "twos += 1";;   # And this to 2, etc.
  34   2) let "threes += 1";;
  35   3) let "fours += 1";;
  36   4) let "fives += 1";;
  37   5) let "sixes += 1";;
  38 esac
  39 }
  40 
  41 echo
  42 
  43 
  44 while [ "$throw" -lt "$MAXTHROWS" ]
  45 do
  46   let "die1 = RANDOM % $PIPS"
  47   update_count $die1
  48   let "throw += 1"
  49 done  
  50 
  51 print_result
  52 
  53 #  The scores should distribute fairly evenly, assuming RANDOM is fairly random.
  54 #  With $MAXTHROWS at 600, all should cluster around 100, plus-or-minus 20 or so.
  55 #
  56 #  Keep in mind that RANDOM is a pseudorandom generator,
  57 #+ and not a spectacularly good one at that.
  58 
  59 #  Randomness is a deep and complex subject.
  60 #  Sufficiently long "random" sequences may exhibit
  61 #+ chaotic and other "non-random" behavior.
  62 
  63 # Exercise (easy):
  64 # ---------------
  65 # Rewrite this script to flip a coin 1000 times.
  66 # Choices are "HEADS" and "TAILS".
  67 
  68 exit 0

As we have seen in the last example, it is best to "reseed" the RANDOM generator each time it is invoked. Using the same seed for RANDOM repeats the same series of numbers. (This mirrors the behavior of the random() function in C.)


Example 9-27. Reseeding RANDOM

   1 #!/bin/bash
   2 # seeding-random.sh: Seeding the RANDOM variable.
   3 
   4 MAXCOUNT=25       # How many numbers to generate.
   5 
   6 random_numbers ()
   7 {
   8 count=0
   9 while [ "$count" -lt "$MAXCOUNT" ]
  10 do
  11   number=$RANDOM
  12   echo -n "$number "
  13   let "count += 1"
  14 done  
  15 }
  16 
  17 echo; echo
  18 
  19 RANDOM=1          # Setting RANDOM seeds the random number generator.
  20 random_numbers
  21 
  22 echo; echo
  23 
  24 RANDOM=1          # Same seed for RANDOM...
  25 random_numbers    # ...reproduces the exact same number series.
  26                   #
  27                   # When is it useful to duplicate a "random" number series?
  28 
  29 echo; echo
  30 
  31 RANDOM=2          # Trying again, but with a different seed...
  32 random_numbers    # gives a different number series.
  33 
  34 echo; echo
  35 
  36 # RANDOM=$$  seeds RANDOM from process id of script.
  37 # It is also possible to seed RANDOM from 'time' or 'date' commands.
  38 
  39 # Getting fancy...
  40 SEED=$(head -1 /dev/urandom | od -N 1 | awk '{ print $2 }')
  41 #  Pseudo-random output fetched
  42 #+ from /dev/urandom (system pseudo-random device-file),
  43 #+ then converted to line of printable (octal) numbers by "od",
  44 #+ finally "awk" retrieves just one number for SEED.
  45 RANDOM=$SEED
  46 random_numbers
  47 
  48 echo; echo
  49 
  50 exit 0

Note

The /dev/urandom device-file provides a means of generating much more "random" pseudorandom numbers than the $RANDOM variable. dd if=/dev/urandom of=targetfile bs=1 count=XX creates a file of well-scattered pseudorandom numbers. However, assigning these numbers to a variable in a script requires a workaround, such as filtering through od (as in above example) or using dd (see Example 12-51).

There are also other means of generating pseudorandom numbers in a script. Awk provides a convenient means of doing this.


Example 9-28. Pseudorandom numbers, using awk

   1 #!/bin/bash
   2 # random2.sh: Returns a pseudorandom number in the range 0 - 1.
   3 # Uses the awk rand() function.
   4 
   5 AWKSCRIPT=' { srand(); print rand() } '
   6 #            Command(s) / parameters passed to awk
   7 # Note that srand() reseeds awk's random number generator.
   8 
   9 
  10 echo -n "Random number between 0 and 1 = "
  11 
  12 echo | awk "$AWKSCRIPT"
  13 # What happens if you leave out the 'echo'?
  14 
  15 exit 0
  16 
  17 
  18 # Exercises:
  19 # ---------
  20 
  21 # 1) Using a loop construct, print out 10 different random numbers.
  22 #      (Hint: you must reseed the "srand()" function with a different seed
  23 #+     in each pass through the loop. What happens if you fail to do this?)
  24 
  25 # 2) Using an integer multiplier as a scaling factor, generate random numbers 
  26 #+   in the range between 10 and 100.
  27 
  28 # 3) Same as exercise #2, above, but generate random integers this time.

The date command also lends itself to generating pseudorandom integer sequences.