第二道题
时间:2008-01-29 来源:hoog
题2.在SHELL中,变量RANDOM可以产生随机数。现设置基础字符表为[0-9a-zA-Z],根据基础表生成一定长度的随机字符串,长度可指定。分别使用正序和倒序显示字串。
#!/bin/bash
#set -x
LEN=${1:?"required an numeric."}
num=0
index=0
charset=(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)
while [ $num -lt $LEN ]
do
num=`expr $num + 1`
tmp=$RANDOM
if [ $tmp -gt 62 ]
then
index=`expr $tmp - $tmp / 62 \* 62`
resSet[$num]=${charset[index]}
tmp=`expr $1 - $num`
IresSet[$tmp]=${resSet[num]}
else
index=$tmp
resSet[$num]=${charset[index]}
tmp=`expr $1 - $num`
IresSet[$tmp]=${resSet[num]}
fi
done
num=0
while [ $num -lt $LEN ]
do
num=`expr $num + 1`
printf "%c" "${resSet[num]}"
done
printf "\n"
num=0
while [ $num -lt $LEN ]
do
printf "%c" "${IresSet[num]}"
num=`expr $num + 1`
done
printf "\n"
#set +x
#set -x
LEN=${1:?"required an numeric."}
num=0
index=0
charset=(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)
while [ $num -lt $LEN ]
do
num=`expr $num + 1`
tmp=$RANDOM
if [ $tmp -gt 62 ]
then
index=`expr $tmp - $tmp / 62 \* 62`
resSet[$num]=${charset[index]}
tmp=`expr $1 - $num`
IresSet[$tmp]=${resSet[num]}
else
index=$tmp
resSet[$num]=${charset[index]}
tmp=`expr $1 - $num`
IresSet[$tmp]=${resSet[num]}
fi
done
num=0
while [ $num -lt $LEN ]
do
num=`expr $num + 1`
printf "%c" "${resSet[num]}"
done
printf "\n"
num=0
while [ $num -lt $LEN ]
do
printf "%c" "${IresSet[num]}"
num=`expr $num + 1`
done
printf "\n"
#set +x
相关阅读 更多 +