[Code Example] Get random element from array using bash script


In this article we will show you a bash script code to get random element from an array. This function will select an element randomly and return. It doesn’t use loops.

Code Example –


random_array_element() {
    local arr=("[email protected]")
    printf '%s\n' "${arr[RANDOM % $#]}"

arr=(yo ho all together hoist the colors high)

random_array_element "${arr[@]}"

# Output:
# all

Inspired from Dylan Araps

Live Demo

Demo might not work in private window (incognito)

Sign Up for Our Newsletters

Get only the best articles delivered to your mail

You May Also Like