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

Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.

auto num generation

Hie. i am having a serious problem and need a solution soon. How do i auto generate a number in linux scripting?

The script, as shown above,

The script, as shown above, will generate a random number...

thanks alot!

thanks alot!

Script to return a random number between two bounds:

Just to extend your first script a little:

newrand=$[ ( $RANDOM % ( $[ $highest - $lowest ] + 1 ) ) + $lowest ]

Nice one. Thanks!

Nice one. Thanks!

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

CAPTCHA
This question is for testing whether you are a human visitor and to prevent automated spam submissions.
4 + 3 =
Solve this simple math problem and enter the result. E.g. for 1+3, enter 4.