Last active
August 26, 2015 21:06
-
-
Save mfdj/9345e0077713f90e3e55 to your computer and use it in GitHub Desktop.
BASH random integer function using /dev/urandom
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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