lundi 16 février 2015

function to get a random element of an array bash [duplicate]


This question already has an answer here:




I have different arrays, representing the options of one function. I would like to randomize these options. I know how to get a random item from an array like that :



declare -a ARRAYISO=(100 200 400 800)
echo ${ARRAYISO["$[RANDOM % ${#ARRAYISO[@]}]"]}


I could obviously do that for each array, like a donkey, but I'd like to make a function taking an array as argument and return the random element.


I'm trying like that:



randArrayElement()
{
randElement=${$1["$[RANDOM % ${#$1[@]}]"]}
echo $randElement
}
randArrayElement ARRAYISO


but it doesn't like my $1... I've tryed with ", ', ` , bash doesn't interpret the $1 var...


Someone knows how to do that ?


Thanks, Mat


Aucun commentaire:

Enregistrer un commentaire