Tuesday, May 7, 2024
22
rated 0 times [  22] [ 0]  / answers: 1 / hits: 6168  / 1 Year ago, sun, december 11, 2022, 10:54:32

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?


More From » command-line

 Answers
5

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"

[#24250] Tuesday, December 13, 2022, 1 Year  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
looweets

Total Points: 52
Total Questions: 114
Total Answers: 111

Location: Turkmenistan
Member since Sat, Apr 16, 2022
2 Years ago
;