Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generating random numbers that conform to a range in Bash

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?

like image 494
Jose Moreno Avatar asked Apr 21 '17 03:04

Jose Moreno


People also ask

How do you generate random numbers in bash?

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.

How can I generate a random number within a range but exclude some?

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.

What does [- Z $1 mean in bash?

$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.


2 Answers

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

like image 132
Marcos Casagrande Avatar answered Oct 18 '22 19:10

Marcos Casagrande


Try the following (pure BASH):

   low=10
   hgh=45
   rand=$((low + RANDOM%(1+hgh-low)))
like image 29
Fritz G. Mehner Avatar answered Oct 18 '22 18:10

Fritz G. Mehner