Mark Jensen

Invoke Theory. Apply Boundry Conditions

  • Lab Notebook
  • home
  • blog
  • About
  • Art
  • Events
  • References
  • MHCPC
Courtesy of Oleg Alexandrov. 2007. Random Walk In2d Closeup. Portable Network Graphic. Wikimedia Commons. http://bit.ly/1Brvcri.

Courtesy of Oleg Alexandrov. 2007. Random Walk In2d Closeup. Portable Network Graphic. Wikimedia Commons. http://bit.ly/1Brvcri.

Generating Random Numbers in a Linux Shell Script

March 25, 2015 by Mark Jensen in Random Numbers, Programming

Peter Samuleson provided the Linux/Korn shell code for making random numbers using the built in random number generator device /dev/random. He provides the code for signed and unsigned 16 and 32-bit numbers. He uses the od (Octal Dump) command to convert the binary bits from the Linux random file into decimal numbers.

Thus, in Linux, you can get truly random integers quite easily:
exec 19< /dev/random # or you could open /dev/random each time in each fx

random_s32 () { od -An -td4 -N4 <&19; }# signed 32-bit
random_u32 () { od -An -tu4 -N4 <&19; }# unsigned 32-bit
random_s16 () { od -An -td2 -N2 <&19; }# signed 16-bit
random_u16 () { od -An -tu2 -N2 <&19; }# unsigned 16-bit
random_u31 () { local x=$(random_s32); echo ${x#*-}; }
random_u15 () { local x=$(random_s16); echo ${x#*-}; }
# of course you can adapt the above to any other sort of int...

Note: You can also use /dev/urandom if you do not need the full randomness provided by the original. If you depend upon the quality of the randomness of the sequence, e.g., cryptology, you should test the  generator for robustness before you put your mortgage on the line.

Samuleson, Peter. 2001. “Limited Random Numbers in Korn Shell Scripts: Comment #13.” Education. Linux Forum. February 19. http://bit.ly/1CYSj3o.

March 25, 2015 /Mark Jensen
Linux, Shell
Random Numbers, Programming
$\setCounter{0}$
  • Newer
  • Older
blog RSS

Powered by Squarespace