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
Latest posts by ZIADI Mohamed Ali (see all)
- How to show mounted devices in Linux? - July 25, 2017
- How to use Positional parameters and special variables in Linux - June 28, 2017
- Linux: Connect to your WiFi network through CLI? - June 25, 2017
- How to find a file in Linux? - March 19, 2017
- Mysql: How to find table and database size? - January 9, 2017