Accessing random array element in ZSH
feh
is an image viewer, just ignore that part... you want just the second part.
Basically, to access a random array element you want something like ${arr[${ri}]}
where ri
is $(( $RANDOM % ${#arr[@]} + 1))
that is, ri
is a random index of the array arr
Now, $RANDOM % N
resolves to a random number from 0
to N-1
. In this case N
is the array length ${#arr[@]}
(number of elements) but since array indexing starts from 1
in zsh
you have to add one ( + 1
) so that $(( $RANDOM % ${#arr[@]} + 1 ))
returns a value from 1
to N
.
So e.g. to print a random element of the array:
print -r -- ${arr[$(( $RANDOM % ${#arr[@]} + 1 ))]}
Or simply, as array indices are parsed as arithmetic expressions:
print -r -- "$arr[RANDOM % $#arr + 1]"
When using that csh-style syntax (when the expansion is not in braces), the quotes are necessary in order for zsh
to parse the subscript; alternatively, this could be written $arr[RANDOM%$#arr+1]
or ${arr[RANDOM % $#arr + 1]}
(ksh-style).