How to generate random number in Bash?

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


Solution 1:

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

Solution 2:

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.

Solution 3:

You can also use shuf (available in coreutils).

shuf -i 1-100000 -n 1

Solution 4:

Try this from your shell:

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

Here, -t d specifies that the output format should be signed decimal; -N 1 says to read one byte from /dev/urandom.