How do I get randomness in command-line?
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:
file0.jpg
file1.jpg
file2.jpg
file3.jpg
And then you can pick a random one with
# output a random file from file0.jpg to file3.jpg
echo "file$((RANDOM % 4)).jpg"
According to @neon_overload answer (using RANDOM
),
I can put RANDOM
in example script as follows (for 4 commands):
#!/bin/bash
random_selection=$((RANDOM % 4))
case $random_selection in
0)
<command_1>
;;
1)
<command_2>
;;
2)
<command_3>
;;
3)
<command_4>
;;
esac
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.