3

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 which takes an array as argument and returns a random element.

I'm trying with:

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...

bschlueter
  • 3,817
  • 1
  • 30
  • 48

1 Answers1

5

Change your function to:

randArrayElement(){ arr=("${!1}"); echo ${arr["$[RANDOM % ${#arr[@]}]"]}; }

and call it as:

randArrayElement "ARRAYISO[@]"
anubhava
  • 761,203
  • 64
  • 569
  • 643
  • Anubhava, this fucntion puts a \n after the value when I call it, how can I remove it? (I use this output in another command which doesn't work because of that), thanks! – matthieu matthieu Feb 21 '15 at 16:29
  • That is due to `echo` command. Use `echo -n ${arr["$[RANDOM % ${#arr[@]}]"]};` – anubhava Feb 21 '15 at 16:33
  • When I tried the code I get an error `line 11: RANDOM % 0: division by 0 (error token is "0")`. Could you please elaborate more about how to use this function? – Burak Kaymakci Mar 22 '21 at 11:52
  • Just make sure you're passing an array to this function – anubhava Mar 22 '21 at 14:09