Have you ever tried to write Bash shell script and need a random number generator? Here provides 2 ways to achieve this.
1. Use the Built-in variable $RANDOM of Bash
$RANDOM is a built-in variable of Bash, it can be used to generate a random number. It's very easy to use, we can use echo to get its value. Here is the example:$ echo $RANDOM 4371 $ echo $RANDOM 20269 $ |
$ for i in {1..3}; do echo $RANDOM; done 11434 9696 32237 $ |
The number generated by $RANDOM is between 0 and 32767, here is the explanation in detail.
If you want another range, you can use the following method to generate it. Here we create a shell function random_range, which can accept up to 2 arguments. If there is only one argument, it will generate random number between 0 and first argument. Yet if there is 2 arguments, these two numbers will be the lower bound and upper bound of generated numbers. (To keep it simple in the example, there is no strict checking mechanism, please make sure the second argument is larger than the first one).
function random_range() { if [ "$#" -lt "2" ]; then echo "Usage: random_range <low> <high>" return fi low=$1 range=$(($2 - $1)) echo $(($low+$RANDOM % $range)) } |
Here is the execution results:
$ random_range 10 Usage: random_range <low> <high> $ random_range 10 30 18 $ random_range 10 30 13 $ random_range 10 30 10 $ random_range 10 300 85 $ random_range 10 300 221 $ random_range 10 300 103 $ |
2. Use the special file /dev/urandom
There are 2 special files in Linux-like system: dev/random and dev/urandom. They are used to provide the random number for Kernel.urandom is the one which is proper to act as a normal use in user space.The following command utilizes the od command to generate a random number between 0 and 32767, which is exactly the same as above $echo $RANDOM command where the random number is 16-bits wide.
$ od -vAn -N2 -i /dev/urandom 6484 $ od -vAn -N2 -i /dev/urandom 25989 $ |
The od command alone with /dev/urandom can yet generate a much larger random number. Below is an example with 32-bits wide random number which is located in the range of 0 ~ 2147483645.
$ od -vAn -N4 -tu4 /dev/urandom 2981514769 $ od -vAn -N4 -tu4 /dev/urandom 1055285400 $ |
No comments:
Post a Comment