bash-logo

 

Bash function $RANDOM

To generate a random integer we can use the internal bash function $RANDOM.
This functions returns integer between 0 and 32767.

Example:

[www1.linuxnix] root:~ # i=$RANDOM
[www1.linuxnix] root:~ # echo $i
23770
[www1.linuxnix] root:~ # j=$RANDOM
[www1.linuxnix] root:~ # echo $j
3577

To generate a random integer between 1 and 1000, you can use $RANDOM like below:

$(((RANDOM%1000+1)))

Note : $(((RANDOM%1000))) will generate integer between 0 and 999.

Examples:

[www1.linuxnix] root:~ # i=$(((RANDOM%1000+1)))
[www1.linuxnix] root:~ # echo $i
895
[www1.linuxnix] root:~ # j=$(((RANDOM%1000+1)))
[www1.linuxnix] root:~ # echo $j
316

 

/dev/random and /dev/urandom

For bigger integer random generation we can use /dev/random and /dev/urandom which can interact with kernel’s random number generator. We will use the od command for that :

od : dump files in octal and other formats

we will use arguments :
-A or –address-radix=RADIX : output format for file offsets; RADIX is one of [doxn], for Decimal, Octal, Hex or None
-N or –read-bytes=BYTES : limit dump to BYTES input bytes
-t or –format=TYPE : select output format or formats

[www1.linuxnix] root:~ # od  -An -N8 -tu8 < /dev/urandom
 11055529178234849100
[www1.linuxnix] root:~ # od -An -N4 -tu4 < /dev/random
 3202521020

I hope that this blog helped you. Please visit our blog website for other interesting blogs and feel free to leave your feedbacks and comments. Till next time

The following two tabs change content below.
I am a hands-on, competent Linux system engineer with 9 years’ experience. I have a strong performance background in wide variety of professional Linux system support including monitoring, configuration, troubleshooting and maintenance. I have worked on numerous projects from concept to completion. A specialist in LAMP platforms, I take pride in administrating Linux systems and regularly refresh my skills to ensure I keep up with ongoing developments and new technologies.