For example,
echo "$(( ($(od -An -N2 -i /dev/random) )%(1000-0+1) ))"
can be used. But it doesn't scale for bigger numbers.
How can I get a random (/dev/random) number between 0 and 999999999 in bash?
I'd use:
shuf -i0-999999999 -n1
although there is no guarantee that shuf uses /dev/random. With GNU shuf you can specify --random-source=/dev/random if you really want to.
IIRC, FreeBSD (and probably Mac OS X) call this utility shuffle, and it takes slightly different arguments (shuffle -n1000000000 -p1).
If you really want to use /dev/random directly, you can generate a four-byte number by using od -An -N4 -tu4 but remember that there is a bias generated by using %1000000000, since 232 is not divisible by 1000000000. To correct for that, in the particular case of generating random numbers in the range 0-999999999, you need to reject the four-byte random number if it is greater than or equal to 4000000000.
cat /dev/random | tr -cd 0-9 | dd bs=1 count=9
Cat random data from /dev/random, delete all except 0, 1, ... 9; then wait only for 9 digits with dd.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With