Often you may want to select one or more random elements from an array in Bash.
The easiest way to do so is by using the following syntax:
random_element=$(printf "%s\n" "${my_array[@]}" | shuf -n 1)
This particular example selects one random element from the array named my_array and stores the results in a variable named random_element.
Here is what the various commands do:
- printf “%s\n” “${my_array[@]}: Prints each element in the array
- shuf: “Shuffles” the elements in a random order
- -n: Specifies the number of elements to return
To select a different number of elements, simply change the 1 to a different number.
The following example shows how to use this syntax in practice.
Example: How to Select Random Elements from an Array in Bash
Suppose that we create the following array in Bash named my_array that contains the names of various basketball teams:
my_array=(Mavs Hawks Spurs Kings Celtics Lakers Nets)
Suppose that we would like to randomly select one team from this array.
We can use the following syntax to do so:
random_element=$(printf "%s\n" "${my_array[@]}" | shuf -n 1)
echo $random_element
The following screenshot shows how to use this syntax in practice:

Note that when we use the echo command to view the contents of $random_element we can see that it contains the team name Mavs from the array.
Note that we can change the number after the -n operator in the shuf command to instead select several random elements from the array.
For example, we can use the following syntax to instead randomly select three team names from the array:
random_elements=$(printf "%s\n" "${my_array[@]}" | shuf -n 3)
echo $random_elements
The following screenshot shows how to use this syntax in practice:

This time we can see that the teams Spurs, Kings and Lakers were randomly selected.
Feel free to use similar syntax to select N random elements from your own array.
Related Tutorials
The following tutorials explain how to perform other common tasks in Bash:
Bash: How to Generate Random Number in Range
Bash: How to Select Random Lines from a File
Bash: How to Select Random Files from Directory
