Thursday, September 20, 2007

Linux Shell Script - Random number generation

A small note to generate random numbers in Linux scripts:

  • To Generate Random numbers between 0 to 10:
echo $[($RANDOM % 10)]


  • To Generate Random numbers between 1 to 10:

echo $[($RANDOM % 10) + 1]



  • To Generate Random numbers between 30 to 40:

my_random is a function which accept two integers,

#! /bin/bash

my_random()

{

number=$[($RANDOM % $2) + 1]

while [ $number -lt $1 ]

do

number=$[($RANDOM % $2) + 1]

done

echo $number

}

my_random 30 40

1 comment:

tuxthink said...

Hi
Thanks for info.