shell的随机数
bash默认有一个$RANDOM的变量, 默认范围是0~32767.
[root@server shell02]# echo $RANDOM 15832 [root@server shell02]# set |grep RANDOM RANDOM=15832 [root@server shell02]#
产生0~1之间的随机数
[root@server shell02]# echo $[$RANDOM%2] 0 [root@server shell02]# echo $[$RANDOM%2] 0 [root@server shell02]# echo $[$RANDOM%2] 1
产生0~2的随机数
[root@server shell02]# echo $[$RANDOM%3] 1 [root@server shell02]# echo $[$RANDOM%3] 2 [root@server shell02]# echo $[$RANDOM%3] 1 [root@server shell02]# echo $[$RANDOM%3] 2 [root@server shell02]#
产生1~2之间的随机数
[root@server shell02]# echo $[$RANDOM%2+1] 1 [root@server shell02]# echo $[$RANDOM%2+1] 2 [root@server shell02]# echo $[$RANDOM%2+1] 1 [root@server shell02]# echo $[$RANDOM%2+1] 2
产生50~100之间的随机数
[root@server shell02]# echo $[$RANDOM%51+50] 63 [root@server shell02]# echo $[$RANDOM%51+50] 90 [root@server shell02]# echo $[$RANDOM%51+50] 77 [root@server shell02]# echo $[$RANDOM%51+50] 88
产生三位数的随机数
[root@server shell02]# echo $[$RANDOM%900+100] 713 [root@server shell02]# echo $[$RANDOM%900+100] 686 [root@server shell02]# echo $[$RANDOM%900+100] 474 [root@server shell02]# echo $[$RANDOM%900+100] 202
总结一下
产生一个n~m范围内的随机数
使用$RANDOM取余m-n+1,之后加上n就可以了
猜数字游戏
#!/bin/bash echo "猜一个1-100的整数,猜对砸蛋:" num=$[$RANDOM%100+1] while true do read -p "请猜:" gnum if [ $gnum -gt $num ];then echo "大了" elif [ $gnum -lt $num ];then echo "小了" else echo "对了" break fi done echo "砸蛋"