Skip to content

Instantly share code, notes, and snippets.

@mfdj
Last active August 26, 2015 21:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mfdj/9345e0077713f90e3e55 to your computer and use it in GitHub Desktop.
Save mfdj/9345e0077713f90e3e55 to your computer and use it in GitHub Desktop.
BASH random integer function using /dev/urandom
function rand_int {
local min=$1
local max=$2
# dd if=/dev/urandom bs=1 count=1 <-- grab a single 1-byte frame from /dev/urandom
# | od -An -vtu1 <-- convert raw-binary to a decimal
# | tr -d ' ' | tr -d "\n"` <-- trim spaces and line-breaks from output of od (gotta be better way)
local randByte=`dd if=/dev/urandom bs=1 count=1 2> /dev/null | od -An -vtu1 | tr -d ' ' | tr -d "\n"`
# printf "%.0f" <-- prints a float with zero decimal places
# `
# echo "$min + ($randByte/256) * ($max - $min)" <-- sane-looking mathematical expression
# | bc -l <-- bc executes the maths (-l for float precision)
# `
printf "%.0f" `echo "$min + ($randByte/256) * ($max - $min)" | bc -l`
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment