Random number from a range in a Bash Script Random number from a range in a Bash Script shell shell

Random number from a range in a Bash Script


shuf -i 2000-65000 -n 1

Enjoy!

Edit: The range is inclusive.


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

jot -r 1  2000 65000


According to the bash man page, $RANDOM is distributed between 0 and 32767; that is, it is an unsigned 15-bit value. Assuming $RANDOM is uniformly distributed, you can create a uniformly-distributed unsigned 30-bit integer as follows:

$(((RANDOM<<15)|RANDOM))

Since your range is not a power of 2, a simple modulo operation will only almost give you a uniform distribution, but with a 30-bit input range and a less-than-16-bit output range, as you have in your case, this should really be close enough:

PORT=$(( ((RANDOM<<15)|RANDOM) % 63001 + 2000 ))