Re: How do i generate random integer using shell script only?

From: Heiner Steven (heiner.steven_at_nexgo.de)
Date: 08/12/03


Date: Tue, 12 Aug 2003 22:43:29 +0200

Christophe Le Gal wrote:
> [fu2 comp.unix.shell]
>
>>I need to generate a random integer using a unix shell script only (no perl).
>>nice to have - if it would be multi (unix) platform supportive.
>>
>>Any ideas?
>
> On some system (well on linux, at least) you have a device file
> called /dev/random.
> hexdump -d /dev/random
> will then give you some random number.
>
> Else you still can program a simple random generator will expr
> x = `expr "(" $x "*" $A + $B ")" % $C`
> with init value for x taken from
> date +"%N"
>
> If you only need one random value in your script, and the script
> is to be lauche manually (I mean not from another script
> that lauch several of them in a loop),
> then date +"%N" might be an acceptable random value.
>
> I'm not sure %N is present in all date version though.

The script "rand" prints a random number. It uses one of
the following methods to derive it (in order of preference):

 1. /dev/urandom # Solaris 9, Linux
 2. $RANDOM # ksh, ksh93, BASH
 3. date, process id # otherwise

I tested it with Solaris and Linux, but it should
run with other Unix dialects as well:

    http://www.shelldorado.com/scripts/cmds/rand

Heiner

-- 
 ___ _
/ __| |_ _____ _____ _ _     Heiner STEVEN <heiner.steven@nexgo.de>
\__ \  _/ -_) V / -_) ' \    Shell Script Programmers: visit
|___/\__\___|\_/\___|_||_|   http://www.shelldorado.com/


Relevant Pages

  • Re: Gerber to G-Code, Help needed.
    ... perfectly from eagle but i'll like to be able to import a gerber file, ... then convert to G-Code. ... A couple months ago I wrote a similar script in the TCL language. ... set diam [expr ] ...
    (sci.electronics.cad)
  • Re: 64-bit arithmetic in scripts?
    ... Dan Nelson has kindly explained everything: ... I haven't thought about using expr. ... > If you want your script to work on both, you'll have to do a feature ... > calling expr, and finally fall back on calling bc. ...
    (freebsd-questions)
  • Re: 64-bit arithmetic in scripts?
    ... expr does 64-bit math by default. ... If you want your script to work on both, you'll have to do a feature ... calling expr, and finally fall back on calling bc. ...
    (freebsd-questions)
  • Re: random password
    ... > like $$ or timeto set the seed in srand. ... seeding the random generator like this is considered insecure. ... >> Is there a way generate some random password in a script and directly ... Al this in a script. ...
    (comp.sys.hp.hpux)
  • Re: Urgent: Need an integer for loop for renaming files
    ... >file.ext) I need to rename all files in order to get ... you say file*.ext above and in part of your script, ... expr: syntax error ...
    (comp.unix.shell)