RANDOM

noun

say it: “RAN-dum” /ˈrændəm/

A bash variable that gives a new whole number from 0 to 32767 every time it is read.

What is RANDOM in bash?

$RANDOM is a new whole number from 0 to 32767 every time a script reads it. The remainder after dividing by a count, %, turns it into a number from 0 up to one less than the count: exactly an array's slot numbers, so it picks a random item.

mapfile -t songs < songs.txt
pick=$((RANDOM % ${#songs[@]}))
echo "Now playing: ${songs[$pick]}"   # Now playing: Paper Lanterns (yours will differ)

In a sentence

  • “RANDOM % 6 gave Sam a slot number from 0 to 5, so the shuffler picked a song.”
  • “Each time the script reads RANDOM, it gets a different number.”

Level: Journeyman · More Unix terms at this level

Updated