There are a number of reasons why you may want to generate a random number in a Bash shell. We are referring to a Bash shell rather than using a programming language such as C++, Java or Python.
Maybe you want to pull a random line from a file.
Maybe you want to generate a random filename.
Maybe you want to get a number for a simple dice game.
Maybe you are playing a guessing game. Maybe you are picking team members and you need a random number for each player.
Whatever it is, it can be done.
Built into the Bash shell, there is a random number generator. It is called $RANDOM. This is a function, not a constant (note the dollar sign in front of the word). Try running the following command:
This will return an integer from 0 to 32767. You can limit the scope of this number if you put a constraint by using a modulo.
echo $(( RANDOM % 10 ))
This will return a number between 0 to 9. Depending on the purpose of the number, zero may not be suitable for your case. Ten is also not included. You can shift one by adding one number.
echo $(( 1 + RANDOM % 10 ))
Rather than returning a number between 0 to 9, this will return a number between 1 to 10. You are adding a one to whatever number is given.