Generate Random Numbers with Bash Scripting

To generate random numbers with bash use the $RANDOM internal Bash function. Note that $RANDOM should not be used to generate an encryption key. $RANDOM is generated by using your current process ID (PID) and the current time/date as defined by the number of seconds elapsed since 1970. The range of returned values is 0 to 32767.

This will return a number between 1 and 100:

NUMBER=$[ ( $RANDOM % 100 )  + 1 ]

Here is a function to dynamically imitate a die:

#!/bin/bash

function roll_die() {

  # capture parameter
  declare -i DIE_SIDES=$1

  # check for die sides
  if [ ! $DIE_SIDES -gt 0 ]; then
    # default to 6
    DIE_SIDES=6
  fi
  
  # echo to screen
  echo $[ ( $RANDOM % $DIE_SIDES )  + 1 ]

}

roll_die 10  # returns 1 to 10
roll_die 2   # returns 1 or 2

Comments

Post new comment

The content of this field is kept private and will not be shown publicly.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Allowed HTML tags: <a> <em> <strong> <cite> <code> <ul> <ol> <li> <dl> <dt> <dd> <h1> <h2> <h3> <h4> <h5> <h6> <pre> <hr>
  • Lines and paragraphs break automatically.

More information about formatting options