Julien Palard

Python Developer and Trainer

[Bashism] How to generate random number without $RANDOM ?

There is a common bashism, that is to use $RANDOM. Typically you'll have to remove bashism while rewriting your scripts for dash or sh. There is a lot of solutions to generate random numbers in many different ways, but I'm not here to pollute the internet demonstrating 42 differents ways to do this, i'll only show you the one I think is the best, and let you comment it if you can do better :-) My solution is to replace $RANDOM by :

$(($(dd if=/dev/urandom count=1 2> /dev/null | cksum | cut -d' ' -f1) % 32768))

Pros :

Cons :

You should simplify it if the [0, 32767] rule has no importance for you, typically if you want a number between 0 and 10, don't do ... % 32768)) % 11)) ...