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:?
#!/bin/bash
<command_1>
<command_2>
<command_3>
.
.
.
<command_n>
Then I want to execute randomly only one command from above possibilities when script is run!
How to do that?
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.
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
According to @neon_overload answer (using
RANDOM
),I can put
RANDOM
in example script as follows (for 4 commands):If you want randomness through an external site rather than one generated by your computer, you can use this script:
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.
You can use
shuf
command from GNU coreutils.Example:
Now, For getting one random entry you can use
-n 1
which outputs first line.Example for printing random number from 1-100:
If you've
file
with following contents:You can also do something like: