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

Posted on Thu 07 April 2011 in blog

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 :

  • Not so long
  • Yield a different number each call (not all replacement for $RANDOM do)
  • Excatly like in bash, it yield a number between 0 and 32767

Cons :

  • Longer than $RANDOM :p
  • /dev/urandom is not present on every systems ...

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)) ...