LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - General (http://www.linuxquestions.org/questions/linux-general-1/)
-   -   Creating random numbers from shell with /dev/random (http://www.linuxquestions.org/questions/linux-general-1/creating-random-numbers-from-shell-with-dev-random-204520/)

khermans 07-13-2004 11:56 AM

Creating random numbers from shell with /dev/random
 
Could someone point me in the right direction for creating random rumbers within a specific range with /dev/random or /dev/urandom? Say that I want to generate numbers between 1 and 5000, how would I do that? Or maybe even between -35 and 79? Thanks in advance...

Kristian Hermansen

ranger_nemo 07-13-2004 01:12 PM

Bash has a "magic" variable called RANDOM. "echo $RANDOM" will give you a random number. I don't know the max value off hand, but it usually returns a number in the tens-of-thousands.

You can set a max value with "$[ ( $RANDOM % max_val ) ]". So, "echo $[ ( $RANDOM % 5000 ) ]" should be [0,5000]. "echo $[ ( $RANDOM % 4999 + 1 ) ]" should be [1,5000]. "echo $[ ( $RANDOM % 114 - 35 ) ]" should be [-35,79].

You can seed RANDOM with "RANDOM=some_value". Maybe use date in seconds... "RANDOM=$(date +%s)".

Search Google for more info.


All times are GMT -5. The time now is 07:23 AM.