volcano
volcano

Reputation: 3582

bash - Selecting random object from an array

I have a function that selects a random object form an array. I have wrapped the internal bash function RANDOM, and implemented my function like that:

function rand() { echo $[ $RANDOM % $2 + $1 ]; }
function rand_obj() { objs=($@); index=$(rand 0 $#); echo ${objs[$index]} ; }

It works just fine, but I would love to learn a way of implementing it without the intermediate array objs. Any ideas? Thanks in advance

Upvotes: 0

Views: 158

Answers (2)

Etan Reisner
Etan Reisner

Reputation: 81052

Does something like this

rand_obj() {
    shift $(( $(rand 1 $#) - 1 )); echo "$1"
}

do what you want?

The above has problems with arguments that end with newlines.

Command Substitution always removes trailing newlines.

To handle that scenario you'd need to stick a dummy character/etc. at the end and remove it at use time. Something like this:

rand_obj() {
    shift $(( $(rand 1 $#) - 1 )); echo "$1x"
}
elem=$(rand_obj ... ... ... ... ...)
elem=${elem%x}

Upvotes: 2

Jason Hu
Jason Hu

Reputation: 6333

there are too many ways. here is almost oneliner, but assume you have no space in your strings, and you never touched IFS:

echo ${ARRAY[@]} | tr ' ' '\n' | shuf -n1

Upvotes: 2

Related Questions