Reading this: http://www.tldp.org/LDP/abs/html/randomvar.html
# If you need a random integer greater than a lower bound,
#+ then set up a test to discard all numbers below that.
FLOOR=200
number=0 #initialize
while [ "$number" -le $FLOOR ]
do
number=$RANDOM
done
echo "Random number greater than $FLOOR --- $number"
echo
# Let's examine a simple alternative to the above loop, namely
# let "number = $RANDOM + $FLOOR"
# That would eliminate the while-loop and run faster.
# But, there might be a problem with that. What is it?
I have been not able to come up with a decent answer to the question in the last comment. That's the way I always generated my pseudorandom numbers in other languages (C/C++, Pascal), and had no problems -- is this something relevant only to Bash?
In programming languages where your random-number generator could give you values up to just below the overflow point, the latter code would have a bug wherein items within the range between MAXINT - FLOOR and MAXINT would overflow.
Bash does not have this bug, but the reference you are reading is evidently written without that awareness.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With