Generating random number between 1 and 10 in Bash Shell Script

Bash

Bash Problem Overview


How would I generate an inclusive random number between 1 to 10 in Bash Shell Script?

Would it be $(RANDOM 1+10)?

Bash Solutions


Solution 1 - Bash

$(( ( RANDOM % 10 )  + 1 ))

EDIT. Changed brackets into parenthesis according to the comment. http://web.archive.org/web/20150206070451/http://islandlinux.org/howto/generate-random-numbers-bash-scripting

Solution 2 - Bash

Simplest solution would be to use tool which allows you to directly specify ranges, like [tag:GNU] shuf

shuf -i1-10 -n1

If you want to use $RANDOM, it would be more precise to throw out the last 8 numbers in 0...32767, and just treat it as 0...32759, since taking 0...32767 mod 10 you get the following distribution

0-8 each: 3277 
8-9 each: 3276

So, slightly slower but more precise would be

while :; do ran=$RANDOM; ((ran < 32760)) && echo $(((ran%10)+1)) && break; done 

Solution 3 - Bash

To generate random numbers with bash use the $RANDOM internal Bash function. Note that $RANDOM should not be used to generate an encryption key. $RANDOM is generated by using your current process ID (PID) and the current time/date as defined by the number of seconds elapsed since 1970.

 echo $RANDOM % 10 + 1 | bc

Solution 4 - Bash

You can also use /dev/urandom:

grep -m1 -ao '[0-9]' /dev/urandom | sed s/0/10/ | head -n1

Solution 5 - Bash

To generate in the range: {0,..,9}

r=$(( $RANDOM % 10 )); echo $r

To generate in the range: {40,..,49}

r=$(( $RANDOM % 10 + 40 )); echo $r

Solution 6 - Bash

Here is example of pseudo-random generator when neither $RANDOM nor /dev/urandom is available

> echo $(date +%S) | grep -o .$ | sed s/0/10/

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionA15View Question on Stackoverflow
Solution 1 - BashOrangeTuxView Answer on Stackoverflow
Solution 2 - BashReinstate Monica PleaseView Answer on Stackoverflow
Solution 3 - BashAbhijeet RastogiView Answer on Stackoverflow
Solution 4 - BashchorobaView Answer on Stackoverflow
Solution 5 - BashThomas BrattView Answer on Stackoverflow
Solution 6 - Bashl0panView Answer on Stackoverflow