Linux shell 命令之RANDOM
Shell系统里面有一个随机变量RANDOM
echo $RANDOM
19451
#!/bin/bash
MAX=5 #产生随机数的总量
i=1 #计数器,初值是1
echo "$MAX random numbers are generated:"
while [ "$i" -le $MAX ]
do
number=$RANDOM
echo $number
let "i=i+1"
done
./random.sh
5 random numbers are generated:
28056
13993
11099
26820
13892
cat seqrand.sh
#!/bin/bash
#set -x
length=6 #随机字串的长度
i=1 #计数器,初值是1
#seq是数字、大小写字母
seq=(0 1 2 3 4 5 6 7 8 9 a b c d e f g h i j k l m n o p q r s t u v w x y z A B C D E F G H I J K L M N O P Q R S T U V W X Y Z)
num_seq=${#seq[@]} #计算seq数组的长度
while [ "$i" -le "$length" ]
do
seqrand[$i]=${seq[$((RANDOM%num_seq))]}
let "i=i+1"
done
#下面是输出结果
echo "The random string is:"
for j in ${seqrand[@]}
do
echo -n $j
done
echo
./seqrand.sh
The random string is:
iG7GZA
cat dice.sh
#!/bin/bash
PIPS=6 #一个骰子有6面
MAX=1000 #投骰子的次数
throw=1 #计数器,初值是1
#下面是6个计数的变量
one=0
two=0
three=0
four=0
five=0
six=0
count() #更新计数的次数
{
case "$1" in
0) let "one=one+1";; #跟$RIPS变量取模为0~5,因此0代表么骰子的1
1) let "two=two+1";;
2) let "three=three+1";;
3) let "four=four+1";;
4) let "five=five+1";;
5) let "six=six+1";;
esac
}
while [ "$throw" -le "$MAX" ]
do
let "dice=RANDOM % $PIPS"
count $dice
let "throw=throw+1"
done
#下面输出统计结果
echo "The statistics results are as follows:"
echo "one=$one"
echo "two=$two"
echo "three=$three"
echo "four=$four"
echo "five=$five"
echo "six=$six"
./dice.sh
The statistics results are as follows:
one=167
two=164
three=155
four=169
five=186
six=159
浙公网安备 33010602011771号