Mailing List Archive

Support open source code!


[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: [tlug] random in bash [Kmail Notification]



On Thu, 7 Mar 2002, Shimpei Yamashita wrote:

> On Thu, Mar 07, 2002 at 07:15:33PM +0900,
> Antony Stace wrote:
>
> > > Do anyone know how to do a "random" in bash ? I guess that would be the
> > > simpliest way to do that.

> Well, if you're going to be platform dependent, you might as well use
> the kernel random number generator.
>
> function rand
> {
> perl -e 'open IN,"/dev/random" or die $!;sysread(IN,$r,4);print unpack("L",$r)'
> }

Hey, no fair pulling out perl -- the rules were you had to use bash :-)

Here are some bash functions to produce (admittedly not very random)
pseudo-random numbers:

----------------8<----------------8<----------------8<----------------
#!/usr/local/bin/bash

maxrand=2147483647
rand=`LANG=C date | tr -d ":-z" | tr -s " " | tr " " '\012' | head -3 | tr -d '\012'`

rand()
{
    cmd="rand=\`expr \( $rand \* 1103515245 + 12345 \) \% 2147483648\`"
    eval $cmd
    echo $rand
}

random()
{
    max=${1:-100}
    cmd="rand=\`expr \( $rand \* 1103515245 + 12345 \) \% 2147483648\`"
    eval $cmd
    random=`expr $max \* $rand / $maxrand`
    echo $random
}
----------------8<----------------8<----------------8<----------------

The magic numbers (and the algorithm) are taken from FreeBSD's
/usr/src/lib/libc/stdlib/rand.c.  The automagical seeding i came up with
on my own.

Examples of use:

rand		# gives a "random" integer between 0 and 2147483647
random 30	# gives a "random" integer i, where 0 <= i < 30
random		# gives random i, 0 <= i < 100  (random defaults to 100)
-- 
Tod McQuillin



Home | Main Index | Thread Index

Home Page Mailing List Linux and Japan TLUG Members Links