If I run ./random.sh 10 45
, it would only return random numbers between 10
and 45
.
I am able to produce the random number using
randomNumber=$((1 + RANDOM % 100))
but now how can I allow user to specify upper and lower limit of random number?
The random number or a range of random numbers can be generated using the $RANDOM variable. It generates a random number between 0 and 32767 by default. But you can set the range of numbers for generating random numbers by dividing the value of $RANDOM with a specific value.
After generating the random number you've to put the "holes" back in the range. This can be achieved by incrementing the generated number as long as there are excluded numbers lower than or equal to the generated one. The lower exclude numbers are "holes" in the range before the generated number.
$1 means an input argument and -z means non-defined or empty. You're testing whether an input argument to the script was defined when running the script. Follow this answer to receive notifications.
You can use shuf
#!/bin/bash
# $1: Lower limit
# $2: Upper limit
# Todo Check arguments
shuf -i $1-$2 -n 1
./random.sh 45 50
Try the following (pure BASH):
low=10
hgh=45
rand=$((low + RANDOM%(1+hgh-low)))
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