Friday, May 21, 2010

Methods to Generate a Random digit from 0 to 9 in bash

echo "${RANDOM}" | cut -c 3 | grep .

Note that sometimes you will get nothing...

A more sophisticated way to do this is to use modular arithmatic:

digit="${RANDOM}" && let "digit %= 10" && echo $digit

This will always return a value. Note that the first version is essentially 100-999 mod 100.