How can I generate random numbers in shell scripts?

12:23:00 PM 0 Comments

How can I generate random numbers in shell scripts?

   This depends on the shell, and the facilities available from the
   OS.

   a. Some shells have a variable called RANDOM, which evaluates to a
      different value every time you dereference it. If your shell has
      this variable,

        $ number=$RANDOM will produce a random number.

   b. Some systems have a /dev/urandom device, which generates a
      stream of bits. This can be accessed using the dd(1) utility. An
      example of this (from a more extensive discussion of different
      techniques at http://www.shelldorado.com/scripts/cmds/rand)

        n=`dd if=/dev/urandom bs=1 count=4 2>/dev/null | od -t u4 | \
        awk 'NR==1 {print $2}'`

        also:

        od -vAn -N4 -tu4 < /dev/urandom

   c. Use a utility such as awk(1), which has random number generation
      included. This approach is the most portable between shells and
      operating systems.

        awk 'BEGIN {srand();print rand()}'

      Note that this doesn't work with older versions of awk. This
      requires a version supporting the POSIX spec for srand(). For
      example, on Solaris this will not work with /usr/bin/awk, but
      will with nawk or /usr/xpg4/bin/awk.

      Also, if you call this line more than once within the same
      second, you'll get the same number you did the previous time.