Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get a random (/dev/random) number between 0 and 999999999 in bash?

Tags:

bash

random

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?

like image 586
adrelanos Avatar asked Sep 01 '25 22:09

adrelanos


2 Answers

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.

like image 93
rici Avatar answered Sep 03 '25 17:09

rici


 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.

like image 44
osgx Avatar answered Sep 03 '25 18:09

osgx