Jose Moreno
Jose Moreno

Reputation: 61

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?

Upvotes: 6

Views: 7156

Answers (4)

spanky
spanky

Reputation: 31

The trouble with modulo is that $RANDOM % N, unless N is a power of 2, does not have an equal probability distribution for all results: How to generate random number in Bash?. Per man bash, $RANDOM produces a number between 0 and 32,767 (2**15-1). This may not matter much in some situations, but by rewriting the expression slightly we do get an equal distribution.

for i in {0..10}; do echo -n "$((RANDOM*36/32768 + 10)) "; done; echo

A bash script with a user-selectable range:

#!/bin/bash
LOW=$1
HIGH=$2
echo $((RANDOM * ($HIGH-$LOW+1) / 32768 + LOW))

You will want to do some parameter checking also.

Upvotes: 3

Fritz G. Mehner
Fritz G. Mehner

Reputation: 17188

Try the following (pure BASH):

   low=10
   hgh=45
   rand=$((low + RANDOM%(1+hgh-low)))

Upvotes: 3

jehutyy
jehutyy

Reputation: 364

The idea is to set your range at a default lower bound, say 10, with a higher bound, say 45. So you adjust the lower bound like this : $RANDOM % 45 + 10, don't you?

But there is a problem with this solution, it assumes that you'll always be between 0 + 10 and 45 so in fact it works until you reach 35 (35 + 10 = 45 your higher bound), anymore than 35 will be out of your bounds.

The solution in order to stay in the range is to do $RANDOM % (higher_b - lower_b) which will allow you to stay in higher bound then to add lower bound which gives you :

$RANDOM % (45 -10) + 10

example wrong output:

for i in {0..10};do printf $[RANDOM % 45 + 10]" ";done
47 31 53 23 36 10 22 36 11 25 54

example right output:

for i in {0..10};do printf $[RANDOM % 35 +10]" ";done
39 44 14 12 38 31 25 13 42 33 16

You can also write RANDOM % (higher - lower +1) if you want your index to include higher bound.

Upvotes: 2

Marcos Casagrande
Marcos Casagrande

Reputation: 40374

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

Upvotes: 4

Related Questions