Shell – Set variable to random item in array

shell-script

In bash, I have an array containing a list of links, e.g.

http://xkcd.com/archive
http://what-if.xkcd.com/
http://blag.xkcd.com/
http://store.xkcd.com/

I also have a variable named $URL. I would like to set the variable $URL to a random item in the list.

Best Answer

You could use RANDOM variable defined by bash:

URL=${URLLIST[ $(( RANDOM % ${#URLLIST[@]} )) ] }

where URLLIST is the an array containng your urls:

URLLIST=( \
    "http://xkcd.com/archive" \
    "http://what-if.xkcd.com/" \
    "http://blag.xkcd.com/" \
    "http://store.xkcd.com/" \
)
Related Question