Ubuntu – How to get randomness in command-line

command line

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?

Best Answer

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"