tags:

views:

679

answers:

6

How to generate a random number in bash?

+13  A: 

Please see $RANDOM:

$RANDOM is an internal Bash function (not a constant) that returns a pseudorandom integer in the range 0 - 32767. It should not be used to generate an encryption key.

Andrew Hare
A: 

There is $RANDOM. I don't know exactly how it works. But it works. For testing, you can do :

echo $RANDOM

Antoine Claval
+2  A: 

If you are using a linux system you can get a random number out of /dev/random or /dev/urandom. Be carefull /dev/random will block if there are not enough random numbers available. If you need speed over randomness use /dev/urandom.

These "files" will be filled with random numbers generated by the operating system. It depends on the implementation of /dev/random on your system if you get true or pseudo random numbers. True random numbers are generated with help form noise gathered from device drivers like mouse, hard drive, network.

You can get random numbers from the file with dd

Janusz
+7  A: 

Yes, $RANDOM. It's often useful in combination with simple shell arithmetic. For instance, to generate a random number between 1 and 10:

$ echo $[ 1 + $[ RANDOM % 10 ]]
5

The actual generator is in variables.c, the function brand(). Older versions were a simple linear generator. Version 4.0 of bash uses a generator with a citation to a 1985 paper, which presumably means it's a decent source of pseudorandom numbers. I wouldn't use it for a simulation (and certainly not for crypto), but it's probably adequate for basic scripting tasks.

If you're doing something that requires serious random numbers you can use /dev/random or /dev/urandom if they're available. Ie:

$ dd if=/dev/urandom count=4 bs=1 | od -t d
Nelson
A: 

you can also get random number from awk

awk 'BEGIN {
   # seed
   srand()
   for (i=1;i<=1000;i++){
     print int(1 + rand() * 100)
   }
}'
ghostdog74
A: 

Try this from your shell:

$ od -A n -t d -N 1 /dev/urandom

Barun