0

I want to write a Shell Script. The task is, that I have to pick a random number. But the numbers must be one of the following three. 5,10,15 So if "let's say" 'a' is smaller than 5, I have to pick randomly a number of 5,10 or 15. How can I do that?

Mike
  • 174
  • 1
  • 11
  • What if the number `a`, is greater than 5? – Inian Dec 09 '16 at 07:29
  • Possible duplicate of [Random number from a range in a Bash Script](http://stackoverflow.com/questions/2556190/random-number-from-a-range-in-a-bash-script) – dimo414 Dec 09 '16 at 07:30

2 Answers2

1

Here's a hint to help you do this.

First, create a variable (array) containing your 3 values : arr = (5 10 15).

Then, create a random number called index and floor it to 2.

Finally, retrieve the number ${arr[$index]}.

Val Berthe
  • 1,899
  • 1
  • 18
  • 33
  • Your link suggests using modulo, not floor. But even [modulo isn't sufficient](http://stackoverflow.com/q/10984974/113632) for uniform random numbers in a given range. – dimo414 Dec 09 '16 at 07:31
0

Try the following

#!/bin/bash

arr=(5 10 15);
picked_element=${arr[$(($RANDOM % 3))]};
echo $picked_element;
jsalatas
  • 255
  • 2
  • 9