How to generate random number in Bash?

woakas picture woakas · Jul 28, 2009 · Viewed 232.2k times · Source

How to generate a random number within a range in Bash?

Answer

Nelson picture Nelson · Jul 28, 2009

Use $RANDOM. It's 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 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:

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