1. Use the system $RANDOM variables
fdipzone@ubuntu:~$ Echo $RANDOM
17617
The range of the $RANDOM is [0, 32767]
If you need to generate more than 32767 random numbers, you can do so in the following ways.
Example: Generating random numbers of 400000~500000
#!/bin/bash
function rand () {
min=$1
max=$ ($2-$min + 1))
num=$ (($RANDOM +1000000000)) #增加一个10位的数再求余
echo $ ($num% $max + $min)
}
rnd=$ (Rand 400000 500000)
echo $rnd
exit 0
2. Use Date +%s%n
Example: Generating random numbers of 1~50
#!/bin/bash
function rand () {
min=$1
max=$ ($2-$min + 1))
num=$ (date +%s%n)
echo $ ($num%$ max+ $min))
}
rnd=$ (rand 1)
echo $rnd
exit 0
3. Use of/dev/random and/dev/urandom
This column more highlights: http://www.bianceng.cnhttp://www.bianceng.cn/OS/Linux/
/dev/random stores the real-time data of the system's current operating environment, which is a blocking random number generator and sometimes needs to wait for reading.
/dev/urandom non-blocking random number generator, the read operation does not cause blocking.
Example: Using/dev/urandom to generate 100~500 random numbers, use urandom to avoid blocking.
#!/bin/bash
function rand () {
min=$1
max=$ ($2-$min + 1))
num=$ (cat/dev/urandom | head-n | cksum | awk -F ' ' {print} ')
echo $ (($num% $max + $min))
}
rnd=$ (rand)
echo $rnd
exit 0
4. Using the Linux UUID
The UUID full name is a universal unique identifier that contains 32 16 digits, and the '-' connection number is divided into 5 segments. 32 characters in the form of 8-4-4-4-12.
fdipzone@ubuntu:~/shell$ Cat/proc/sys/kernel/random/uuid
FD496199-372A-403E-8EC9-BF4C52CBD9CD
Example: generating 100~500 random numbers using a Linux UUID
#!/bin/bash
function rand () {
min=$1
max=$ ($2-$min + 1))
num=$ (cat/proc/sys/kernel/random/ UUID | Cksum | Awk-f ' {print} ')
echo $ (($num% $max + $min))
}
rnd=$ (rand)
echo $rnd
exit 0
5. Generate Random strings
Example: generating 10-bit random strings
#use date generate a random string
date +%s%n | md5sum | head-c
#use /dev/urandom Generate random string
cat/dev/urandom | head-n | md5s Um | Head-c 10