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

Total
0
Shares

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 –

#!/bin/bash

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