Skip to content

Instantly share code, notes, and snippets.

@timruffles
Created July 11, 2019 13:33
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 timruffles/48db3ee3ace07abfed7dee42cc5156c6 to your computer and use it in GitHub Desktop.
Save timruffles/48db3ee3ace07abfed7dee42cc5156c6 to your computer and use it in GitHub Desktop.
A bad way to generate a random init in a range using only bash built-ins. Useful in a pinch when you aren't sure what external programs are available.
# Gets an int between min max inclusive very inefficiently, but
# only using bash built-ins. More inefficient the smaller the gap
#
# usage: n=$( bad_random_int 1000 2000 )
bad_random_int() {
local min=$1
local max=$2
local n=0
while [[ "$n" -lt "$min" ]] || [[ "$n" -gt "$max" ]]; do
n=$(( $min + $RANDOM ))
done
echo $n
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment