Set variable to random item in array Code Answer

Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of Set variable to random item in array without wasting too much if your time.

The question is published on by Tutorial Guruji team.

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.

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/" 
)
We are here to answer your question about Set variable to random item in array - If you find the proper solution, please don't forgot to share this with your team members.

Related Posts

Tutorial Guruji