How to generate random number in Bash?


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

6/5/2016 10:33:52 AM

Use $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))

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
7/27/2017 8:04:44 AM

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow