1. $RANDOM
[root@localhost ~]# echo $RANDOM
18657
[root@localhost ~]# echo $RANDOM
27754
2. /dev/urandom
[root@localhost ~]# head -1 /dev/urandom | cksum
69246905 784
[root@localhost ~]# head -1 /dev/urandom | cksum
1252023642 30
3. uuid
[root@localhost ~]# cat /proc/sys/kernel/random/uuid | cksum
3058003197 37
[root@localhost ~]# cat /proc/sys/kernel/random/uuid | cksum
531310992 37
产生随机数的原理是利用当前系统的熵池来计算出固定一定数量的随机比特。熵池就是当前系统的环境噪音,熵指的是一个系统的混乱程度,系统噪音可以通过很多参数来评估,如内存的使用,文件的使用量,不同类型的进程数量等
/dev/random 阻塞程序,直到熵池产生新的随机字节才返回
/dev/urandom 不阻塞程序,产生的随机数质量不高
/dev/random will block after the entropy pool is exhausted. It will remain blocked until additional data has been collected from the sources of entropy that are available. This can slow down random data generation.
/dev/urandom will not block. Instead it will reuse the internal pool to produce more pseudo-random bits.
head -200 /dev/urandom | cksum | cut -d" " -f1
cat /proc/sys/kernel/random/uuid | cksum | cut -d" " -f1
# random number ($RANDOM 0~32767)
declare -i n=$RANDOM*10/32768
echo $n # 0~9