PDA

View Full Version : shell random number



ivandn
01-28-2002, 02:48 AM
Hi.

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

Thanks,
Ivan

Unregistered
01-28-2002, 11:40 AM
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....


#!/bin/sh

MAXCOUNT=10
count=1
echo
echo "------------------------------"
while [ "$count" -le $MAXCOUNT ]
do
number=$[ $RANDOM % 20 ]
echo $number
let "count += 1"
done
echo "------------------------------"

starX
01-28-2002, 11:53 PM
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

alex
01-30-2002, 03:01 PM
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