Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Random number from a range in a Bash Script

I need to generate a random port number between 2000-65000 from a shell script. The problem is $RANDOM is a 15-bit number, so I'm stuck!

PORT=$(($RANDOM%63000+2001)) would work nicely if it wasn't for the size limitation.

Does anyone have an example of how I can do this, maybe by extracting something from /dev/urandom and getting it within a range?

like image 268
Jason Gooner Avatar asked Mar 31 '10 20:03

Jason Gooner


People also ask

What does [- Z $1 mean in bash?

$1 means an input argument and -z means non-defined or empty. You're testing whether an input argument to the script was defined when running the script. Follow this answer to receive notifications.

How do you set a range of numbers in bash?

You can iterate the sequence of numbers in bash in two ways. One is by using the seq command, and another is by specifying the range in for loop. In the seq command, the sequence starts from one, the number increments by one in each step, and print each number in each line up to the upper limit by default.


2 Answers

shuf -i 2000-65000 -n 1 

Enjoy!

Edit: The range is inclusive.

like image 105
leedm777 Avatar answered Sep 19 '22 17:09

leedm777


On Mac OS X and FreeBSD you may also use jot:

jot -r 1  2000 65000 
like image 28
errno Avatar answered Sep 21 '22 17:09

errno