Bash Shell Generate Random Numbers

How do I create or generate random numbers (sequence of numbers that lack any pattern), under Bash shell?

The bash shell offers $RANDOM variable (it also works with ksh). From the bash man page:

Each time this is referenced, a random integer between 0 and 32767 is generated. The sequence of random numbers may be initialized by assigning a value to RANDOM. If RANDOM is unset, it loses its special properties, even if it is subsequently reset.

To view $RANDOM, enter:
$ echo $RANDOM
Sample outputs:


You can use the bash loop as follows to test random numbers:

for i in {1..5}; do echo $RANDOM; done

Sample outputs:


You can store it to a variable as follows:

 echo "My move: trying $n..."

You can have a random integer number within a certain range as follows:

# display a random integer <= 200
echo $(( r %= 200 ))
# display random number between 100 and 200.
echo $((RANDOM%200+100))

Here is a sample shell script to find out random TCP port:

# Set a trap to detect spam bots at port 80
# Find out random unused TCP port 
	port=$(( 100+( $(od -An -N2 -i /dev/random) )%(1023+1) ))
	while :
		(echo >/dev/tcp/localhost/$port) &>/dev/null &&  port=$(( 100+( $(od -An -N2 -i /dev/random) )%(1023+1) )) || break
	echo "$port"
echo "Setting Honeypot @ port 80 and real Apache server at port $p..."
# setHoneypot 80 
# setApache $p

Another shell script to setup a random wallpaper. You can call this one from your crontab:

# get images
# find out random one
wallpaper="${files[RANDOM % n]}"
# Kde3 command (may not work with kde4)
# dcop kdesktop KBackgroundIface setWallpaper "$wallpaper" 5
# Gnome command
gconftool-2 --type string --set /desktop/gnome/background/picture_filename "$wallpaper"

Using /dev/urandom or /dev/random

The character special files /dev/random and /dev/urandom provide an interface to the kernel’s random number generator. You can use /dev/urandom as follows:
$ od -vAn -N4 -tu4 < /dev/urandom
Sample outputs:


You can use /dev/random as follows:
$ od -An -N2 -i /dev/random
Sample outputs:


Recommended readings:

See the following man pages:
man 4 random
man bash
man od

Posted by: SXI ADMIN

The author is the creator of SXI LLC and a seasoned sysadmin, DevOps engineer, and a trainer for the Linux operating system/Unix shell scripting. Get the latest tutorials on SysAdmin, Linux/Unix and open source topics via RSS/XML feed or weekly email newsletter.