Take the 2-minute tour ×

How to randomly execute one command within specified list of command? Helpful for randomly choosing startup sound, wallpaper or executing commands.

In General, if I have commands for execution as follows then How do I get randomness:?


Then I want to execute randomly only one command from above possibilities when script is run!

How to do that?

share|improve this question
Practical example: askubuntu.com/a/257471/163331 –  Parto Jul 7 at 5:53
@Parto I already added as answer before –  Pandya Jul 7 at 5:57
I was not trying to answer, was just giving an example where it can be used. –  Parto Jul 7 at 5:58

3 Answers 3

up vote 20 down vote accepted

The variable $RANDOM (actually a bash function) returns a random number from 0 to 32767 inclusive.

You would typically want to limit its range by dividing it by some number and take its remainder, eg.

# output a random number 0 to 3
echo $((RANDOM % 4))

In this simplistic example it'll be very slightly biased for any divisor that doesn't divide equally into 32768 (eg, anything that isn't a power of two), but in your scenario I don't think you'd be troubled by a slight bias.

To pick a random file, you'd name your files something like:


And then you can pick a random one with

# output a random file from file0.jpg to file3.jpg
echo "file$((RANDOM % 4)).jpg"
share|improve this answer
You may want to post it as your own answer - it then could earn you reputation. –  neon_overload Jul 7 at 5:43
helpful use of RANDOM, I accepted! –  Pandya Jul 7 at 5:55
Note that RANDOM % N doesn't result in an equal distribution unless the number of possible values of RANDOM (32768) is divisible by N. To see this, imagine the range of RANDOM was instead 0-4 (5 possible values), and N is 2: there's three ways for $RANDOM % 2 to yield 0 (if $RANDOM yields 0, 2, 4) but two ways for it to yield 1 (1, 3). For an equal distribution you'd have to find the greatest multiple of N that's smaller than 32767 and ignore any random values that are larger than that. In the previous example that'd amount to ignoring 5, which is larger than 4. –  Doval Jul 7 at 14:43
@Doval I said that in my answer, did you see it? –  neon_overload Jul 8 at 2:05
@neon_overload My bad, I missed that bit. –  Doval Jul 8 at 11:42

According to @neon_overload answer (using RANDOM),
I can put RANDOM in example script as follows (for 4 commands):

random_selection=$((RANDOM % 4))

case $random_selection in





share|improve this answer

If you want randomness through an external site rather than one generated by your computer, you can use this script:

curl "http://www.random.org/integers/?num=1&min=$1&max=$2&col=1&base=10&format=plain&rnd=new"

Run as rand (MIN) (MAX) (assuming you save as /usr/bin/rand)

You might have to install curl first (sudo apt-get install curl) if it is not already installed.

share|improve this answer

Your Answer


