Generating random number in shell script

I had to create temporary files with random names with a wide range. We can use $random to generate such numbers but it’s range is less.

Another option is to .$$ which basically gives you the process ID which will be more or less random

PROGNAME=`type $0 | awk ‘{print $3}’`

But again this is also not reliable and there are chances of clashes. So here is the final code which can generate random number withing the range you provide

rnd=$(cat /dev/urandom | tr -dc 0-9 | fold -w${#MAX} | head -1 | sed ‘s/^0*//;’)
[ -z $rnd ] && rnd=0
(( $rnd < $MIN || $rnd > $MAX ))
do :

Uday Ogra

Connect with me at and lets have some healthy discussion :)

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *