linux 中生成随机数

 

001、$RANDOM (0~32767的随机数)

a、

[root@pc1 test1]# echo $RANDOM     ## 直接输出
31128
[root@pc1 test1]# echo $RANDOM
2539
[root@pc1 test1]# echo $RANDOM
23307

 

b、限定范围

[root@pc1 test1]# echo $(($RANDOM % 100))       ##  生成0-99的随机数
26
[root@pc1 test1]# echo $(($RANDOM % 100))
43
[root@pc1 test1]# echo $(($RANDOM % 1000))      ## 生成0-999的随机数
898
[root@pc1 test1]# echo $(($RANDOM % 1000))
310

 

002、使用shuf命令

a、

[root@pc1 test1]# shuf -i 1-100 -n 2
12
76
[root@pc1 test1]# shuf -i 1-100 -n 2
79
23

 

b、

[root@pc1 test1]# shuf -i 1-10000000 -n 2     ## 指定更大的范围; 速度较快
534014
4614802
[root@pc1 test1]# shuf -i 1-10000000 -n 2
1099722
1601413

 

003、使用awk内置函数rand()

[root@pc1 test1]# echo |awk '{print rand()}'                    ## 生成随机数
0.237788
[root@pc1 test1]# echo |awk 'BEGIN{srand()}{print rand()}'      ## 设定种子;种子默认是系统时间;因此命令执行间隔短可能会生成一样的随机数
0.116499
[root@pc1 test1]# echo |awk 'BEGIN{srand()}{print rand()}'
0.893826
[root@pc1 test1]# echo |awk -v seed=$RANDOM 'BEGIN{srand(seed)}{print rand()}'  ## 利用$RANDOM设定种子
0.578206
[root@pc1 test1]# echo |awk -v seed=$RANDOM 'BEGIN{srand(seed)}{print rand()}'
0.419449
[root@pc1 test1]# echo |awk -v seed=$RANDOM 'BEGIN{srand(seed)}{print rand()}'
0.731802

 

004、使用/dev/random和/dev/urandom(用于生成更大的随机数)

[root@pc1 test1]# head -n 10 /dev/random |tr -dc '[:digit:]' |head -c 30 | awk '{print $0}'  
741756911767276997903271522872
[root@pc1 test1]# head -n 10 /dev/urandom |tr -dc '[:digit:]' |head -c 30 | awk '{print $0}'  ## 效率更高
982180777052629384962301968629

 。

 

reference:

01、https://mp.weixin.qq.com/s?__biz=Mzg2Nzk0NDU4NQ==&mid=2247485177&idx=1&sn=020b2e3f32ad54948e5acd686008f97e&chksm=ceb2971ff9c51e09065badcb270df3916e1eb5bc8dfaf2fd77c9be5c240a50b9b6286d5f556e&mpshare=1&scene=23&srcid=0206ftXhcaUn2HrDfNxpSLXS&sharer_shareinfo=b2122fa371d64bb1970124e5be48ebfa&sharer_shareinfo_first=b2122fa371d64bb1970124e5be48ebfa#rd

 

posted @ 2024-02-19 17:16  小鲨鱼2018  阅读(5)  评论(0编辑  收藏  举报