I'm looking way to make bash script that greps output of command and place strings into array and be able to randomly select 1 string from the array for example every minute and place it as variable, time for randomly selecting needs to be configurable.

Command output:

Place of all these strings into array and randomly select one of them and place it as variable

desired result:
strings -> array <- randomly selecting from array every 1 minute and placing string selected as variable for further use 
  • 1
    This is crying out for some example input together with corresponding desired output. – steve May 31 at 14:36
  • Selecting randomly every for example 1 minute, so this 1 minute is the time – niqo May 31 at 14:37
  • randomly selecting happens every minute so next minute random string is selected again, from the array where those string above are stored – niqo May 31 at 14:38
  • capture all at once – niqo May 31 at 14:43

In bash, you can use readarray with command substitution to capture newline-separated outputs into an array; for exmaple:

readarray -t outputs < <(seq 10)

Where I've used seq 10 to produce some output. This results in:

$ declare -p outputs
declare -a outputs='([0]="1" [1]="2" [2]="3" [3]="4" [4]="5" [5]="6" [6]="7" [7]="8" [8]="9" [9]="10")'

To pseudorandomly select one of those elements every minute:

while :
  element=$(( RANDOM % ${#outputs[@]} ))
  sleep 60

Noting that bash arrays start at index zero, the $(( )) arithemtic says to use the value of $RANDOM modulo the number of elements in the outputs array.

  • Nice and simple solution, thanks! – niqo May 31 at 16:49

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.