How to generate a random number within a range in Bash?
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
I like this trick:
echo ${RANDOM:0:1} # random number between 1 and 9
echo ${RANDOM:0:2} # random number between 1 and 99
...
Random number between 0 and 9 inclusive.
echo $((RANDOM%10))
There is $RANDOM. I don't know exactly how it works. But it works. For testing, you can do :
echo $RANDOM
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
You can also use shuf (available in coreutils).
shuf -i 1-100000 -n 1