系统默认随机数$RANDOM, 只能产生0-32767的随机数。
查看上次生成的随机数set | grep RANDOM
案例
1. 随机产生1000个以139开头的电话号码
#!/bin/env bash
# Name: ran_phone.sh
# Desc: 产生1000个以139开头的电话号码,保存到/tmp/phonenum.txt中
# Path: /root/shell/ran_phone.sh
# Usage: /root/shell/ran_phone.sh
# Update: 2019年09月22日15:57:17
# Author: Johnsonsmile
FILE=/tmp/phonenum.txt
for (( i=1;i<=1000;i++ ))
do
{
n1=$[$RANDOM%10]
n2=$[$RANDOM%10]
n3=$[$RANDOM%10]
n4=$[$RANDOM%10]
n5=$[$RANDOM%10]
n6=$[$RANDOM%10]
n7=$[$RANDOM%10]
n8=$[$RANDOM%10]
echo "139$n1$n2$n3$n4$n5$n6$n7$n8" >> $FILE
}&
done
wait
echo "生成电话号码完成..."
查看生成电话号码的个数wc -l /tmp/phonenum.txt
或者grep -c 139 /tmp/phonenum.txt
或者cat -n /tmp/phonenum.txt
2. 随机抽取5个幸运观众,只显示前3个号码和最后4个号码,中间4个用****代替。
取出第n行的数据:head -n /tmp/phonenum.txt | tail -1
#!/bin/env bash
# Name: lottery.sh
# Desc: 从/tmp/phonenum.txt中保存的电话号码,随机抽出5个
# Path: /root/shell/lottery.sh
# Usage: /root/shell/lottery.sh
# Update: 2019年09月22日15:57:17
# Author: Johnsonsmile
FILE=/tmp/phonenum.txt
for i in {1..5}
do
# 获取总行数
total_line=$(wc -l /tmp/phonenum.txt | cut -d' ' -f1)
luck_line=$[$RANDOM%$total_line + 1]
# 取出幸运号码的电话
luck_phone=$(head -$luck_line $FILE | tail -1)
# 显示到屏幕
echo "139****${luck_phone:7:4}"
echo $luck_phone >> /tmp/luck.txt
# 删除已经中奖的号码
sed -i "/$luck_phone/d" $FILE
done
3. 批量创建用户,生成随机密码
#!/bin/env bash
# Name: ran_user.sh
# Desc: 从/tmp/phonenum.txt中保存的电话号码,随机抽出5个
# Path: /root/shell/ran_user.sh
# Usage: /root/shell/ran_user.sh
# Update: 2019年09月23日07:52:50
# Author: Johnsonsmile
# 生成随机密码保存到user_pass.txt
echo user0{1..5}:$[$RANDOM%9000+1000] | tr ' ' '\n' > user_pass.txt
# 循环创建5个用户
for ((i=1;i<=5;i++))
do
user=`head -$i user_pass.txt | tail -1 | cut -d: -f1`
pass=`head -$i user_pass.txt | tail -1 | cut -d: -f2`
useradd $user
echo $pass | passwd --stdin $user
done