Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to select a random item from an array in shell

People also ask

How do you select a random value from an array in Java?

Java has a Random class in the java. util package. Using it you can do the following: Random rnd = new Random(); int randomNumberFromArray = array[rnd.

How do you randomly select an element from an array in C?

What you propose is the best solution there is - choose a random index and then use the element at this index. If your question is how to get a random integer, use the built-in function rand() .


Change the line where you define selectedexpression to

selectedexpression=${expressions[$RANDOM % ${#expressions[@]} ]}

You want your index into expression to be a random number from 0 to the length of the expression array. This will do that.


arr[0]="Ploink Poink"
arr[1]="I Need Oil"
arr[2]="Some Bytes are Missing!"
arr[3]="Poink Poink"
arr[4]="Piiiip Beeeep!!"
arr[5]="Hello"
arr[6]="Whoops! I'm out of memmory!"
rand=$[$RANDOM % ${#arr[@]}]
echo $(date)
echo ${arr[$rand]}

Here's another solution that may be a bit more random than Jacob Mattison's solution (hard to say from the jot manpages):

declare -a expressions=('Ploink' 'I Need Oil' 'Some Bytes are Missing' 'Poink Poink' 'Piiiip Beeeep' 'Hello' 'Whoops I am out of memory')
index=$( jot -r 1  0 $((${#expressions[@]} - 1)) )
selected_expression=${expressions[index]}

Solution using shuf:

expressions=("Ploink Poink" "I Need Oil" "Some Bytes are Missing!" "Poink Poink" "Piiiip Beeeep!!" "Hello" "Whoops! I'm out of memmory!")
selectedexpression=$(printf "%s\n" "${expressions[@]}" | shuf -n1)
echo $selectedexpression

Or probably better:

select_random() {
    printf "%s\0" "$@" | shuf -z -n1 | tr -d '\0'
}

expressions=("Ploink Poink" "I Need Oil" "Some Bytes are Missing!" "Poink Poink" "Piiiip Beeeep!!" "Hello" "Whoops! I'm out of memmory!")
selectedexpression=$(select_random "${expressions[@]}")
echo "$selectedexpression"