9.6. $RANDOM: generate random integer

Note

$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-18. 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 # 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 # May generate toss of the dice.
  77 SPOTS=7   # Modulo 7 gives range 0 - 6.
  78 DICE=2
  79 ZERO=0
  80 die1=0
  81 die2=0
  82 
  83 # Tosses each die separately, and so gives correct odds.
  84 
  85   while [ "$die1" -eq $ZERO ]     # Can't have a zero come up.
  86   do
  87     let "die1 = $RANDOM % $SPOTS" # Roll first one.
  88   done  
  89 
  90   while [ "$die2" -eq $ZERO ]
  91   do
  92     let "die2 = $RANDOM % $SPOTS" # Roll second one.
  93   done  
  94 
  95 let "throw = $die1 + $die2"
  96 echo "Throw of the dice = $throw"
  97 echo
  98 
  99 
 100 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-19. Rolling the 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 zeroes=0        # Must initialize counts to zero.
  11 ones=0          # since an uninitialized variable is null, not zero.
  12 twos=0
  13 threes=0
  14 fours=0
  15 fives=0
  16 sixes=0
  17 
  18 print_result ()
  19 {
  20 echo
  21 echo "ones =   $ones"
  22 echo "twos =   $twos"
  23 echo "threes = $threes"
  24 echo "fours =  $fours"
  25 echo "fives =  $fives"
  26 echo "sixes =  $sixes"
  27 echo
  28 }
  29 
  30 update_count()
  31 {
  32 case "$1" in
  33   0) let "ones += 1";;   # Since die has no "zero", this corresponds to 1.
  34   1) let "twos += 1";;   # And this to 2, etc.
  35   2) let "threes += 1";;
  36   3) let "fours += 1";;
  37   4) let "fives += 1";;
  38   5) let "sixes += 1";;
  39 esac
  40 }
  41 
  42 echo
  43 
  44 
  45 while [ "$throw" -lt "$MAXTHROWS" ]
  46 do
  47   let "die1 = RANDOM % $PIPS"
  48   update_count $die1
  49   let "throw += 1"
  50 done  
  51 
  52 print_result
  53 
  54 # The scores should distribute fairly evenly, assuming RANDOM is fairly random.
  55 # With $MAXTHROWS at 600, all should cluster around 100, plus-or-minus 20 or so.
  56 #
  57 # Keep in mind that RANDOM is a pseudorandom generator,
  58 # and not a spectacularly good one at that.
  59 
  60 # Exercise for the reader (easy):
  61 # Rewrite this script to flip a coin 1000 times.
  62 # Choices are "HEADS" or "TAILS".
  63 
  64 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-20. 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 echo; echo
  28 
  29 RANDOM=2          # Trying again, but with a different seen...
  30 random_numbers    # gives a different number series.
  31 
  32 echo; echo
  33 
  34 # RANDOM=$$  seeds RANDOM from process id of script.
  35 # It is also possible to seed RANDOM from 'time' or 'date'.
  36 
  37 # Getting fancy...
  38 SEED=$(head -1 /dev/urandom | od -N 1 | awk '{ print $2 }')
  39 # Pseudo-random output fetched from /dev/urandom (system pseudo-random "device"),
  40 # then converted to line of printable (octal) numbers by "od",
  41 # finally "awk" retrieves just one number for SEED.
  42 RANDOM=$SEED
  43 random_numbers
  44 
  45 echo; echo
  46 
  47 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-31).