Thread: shell random number

  1. #1
    Registered User ivandn's Avatar
    Join Date
    Oct 2001
    Posts
    49

    shell random number

    Hi.

    Does anyone know how to generate a random number in a shell script?

    Thanks,
    Ivan
    Ivan

  2. #2
    Unregistered
    Guest
    the only way i know how to do it is by using the $RANDOM function...all i know is it's not really the best way to generate a true random number. I"m not really bash scripting guy, but here's a small script that uses $RANDOM. you might want to ask some of the admin types on some of the user groups...This script generates 10 random numbers between 0 and 19....

    Code:
    #!/bin/sh
    
    MAXCOUNT=10
    count=1
    echo
    echo "------------------------------"
    while [ "$count" -le $MAXCOUNT ]
    do
            number=$[ $RANDOM % 20 ]
            echo $number
            let "count += 1"
    done
    echo "------------------------------"

  3. #3
    Registered User
    Join Date
    Aug 2001
    Posts
    202
    The best way to generate a random number in a shell script is to write a c program to generate the random number and then call it from a shell script. More robust scripting langauges usually provide their own facilities for generating random numbers, but bash scripts usually just involve executing small compiled programs anyway. Just capture the output of the compiled program into a shell variable and it'll be all good.

    starX
    www.axisoftime.com

  4. #4
    Registered User alex's Avatar
    Join Date
    Sep 2001
    Posts
    132
    To get a high-quality random number from the linux kernel, use something like this.

    hexdump -n4 -e\"%u\" /dev/random

    the output of /dev/random is based on activity of keyboard/mouse/network and interrupt statistics and can only generate a few random numbers per second. /dev/urandom can be used as an alternative, which is quicker.

    alex

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Random number in range generation.
    By hebali in forum C Programming
    Replies: 19
    Last Post: 03-04-2008, 10:46 AM
  2. adding a number to a number
    By bigmac(rexdale) in forum C Programming
    Replies: 11
    Last Post: 10-24-2007, 12:56 PM
  3. How exactly does the random number generator work?
    By Finchie_88 in forum C++ Programming
    Replies: 6
    Last Post: 08-24-2007, 12:46 AM
  4. random number between negative and positive number
    By anomaly in forum C++ Programming
    Replies: 6
    Last Post: 12-06-2003, 08:40 AM
  5. Random Number Generator
    By Ikurik in forum C++ Programming
    Replies: 16
    Last Post: 08-17-2003, 07:34 PM