Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to generate random number in Bash?

Tags:

bash

shell

random

How to generate a random number within a range in Bash?

like image 786
woakas Avatar asked Jul 28 '09 15:07

woakas


2 Answers

Use $RANDOM. It's often useful in combination with simple shell arithmetic. For instance, to generate a random number between 1 and 10 (inclusive):

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

The actual generator is in variables.c, the function brand(). Older versions were a simple linear generator. Version 4.0 of bash uses a generator with a citation to a 1985 paper, which presumably means it's a decent source of pseudorandom numbers. I wouldn't use it for a simulation (and certainly not for crypto), but it's probably adequate for basic scripting tasks.

If you're doing something that requires serious random numbers you can use /dev/random or /dev/urandom if they're available:

$ dd if=/dev/urandom count=4 bs=1 | od -t d 
like image 72
Nelson Avatar answered Sep 20 '22 06:09

Nelson


Please see $RANDOM:

$RANDOM is an internal Bash function (not a constant) that returns a pseudorandom integer in the range 0 - 32767. It should not be used to generate an encryption key.

like image 43
Andrew Hare Avatar answered Sep 20 '22 06:09

Andrew Hare