6

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?

codeforester
  • 39,467
  • 16
  • 112
  • 140
Jose Moreno
  • 61
  • 1
  • 3

4 Answers4

4

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

Marcos Casagrande
  • 37,983
  • 8
  • 84
  • 98
  • 1
    This use an external tool instead of using bash built-in mechanisms. Thus random.sh become much more a wrapper than a tool by itself. – jehutyy Apr 21 '17 at 08:38
3

Try the following (pure BASH):

   low=10
   hgh=45
   rand=$((low + RANDOM%(1+hgh-low)))
Fritz G. Mehner
  • 16,550
  • 2
  • 34
  • 41
3

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.

Stephen Rauch
  • 47,830
  • 31
  • 106
  • 135
spanky
  • 31
  • 1
2

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.

jehutyy
  • 364
  • 3
  • 11