shell – How to generate random number in Bash?

shell – How to generate random number in Bash?

Use $RANDOM. Its often useful in combination with simple shell arithmetic. For instance, to generate a random number between 1 and 10 (inclusive):

$ echo $((1 + $RANDOM % 10))
3

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 its a decent source of pseudorandom numbers. I wouldnt use it for a simulation (and certainly not for crypto), but its probably adequate for basic scripting tasks.

If youre doing something that requires serious random numbers you can use /dev/random or /dev/urandom if theyre available:

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

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.

shell – How to generate random number in Bash?

You can also use shuf (available in coreutils).

shuf -i 1-100000 -n 1

Leave a Reply

Your email address will not be published.