shell脚本联系(随机取名)


shell脚本联系(随机取名)
 
1、写一个脚本,实现随机选人功能,脚本需传递一个参数进去,如    pick.sh 1 出现结果"家驹”  pick.sh 3 出现结果 "落叶" "jason" "贾诩"等随机结果。 (pick.sh N 其中N可以为不大于总人数的任意数)
 
 
#!/bin/bash
#Author:星空刺
#Date:2013-10-18
#文件名必须是一行一个名字
#设定必须有一个参数
cat << EOF
Warning:
1.Name_file must be a name of a line!if not,please enter ctrl+c!
2.\$1 must be exist and \$1 is an int greater than zero!
3.\$1 must be between 0 and the maximum number of names!
***************************************************************
EOF
[ $# -le 0 ] && echo 'Error:$1 must be exist and $1 is an int greater than zero!' && exit 
#名字列表文件路径
read -p 'Please input your name_file_path:' name_path
echo "***************************************************************"
#获取一个数组赋值模式列表
[ -z $name_path ] && echo 'Name_file does not exist' && exit
while read line;do
    name=(${name[*]} $line)
done < $name_path
#获取数组元素总个数
new_name_c=${#name[@]}
#判定脚本的参数是否在0~数组元素个数之间
echo "The current file contains the names of $new_name_c!"
[ $1 -gt $new_name_c ] || [ $1 -lt 0 ] && echo 'But $1 must be between 0 and the maximum number of names!' && exit
echo "***************************************************************"
#利用for循环,循环脚本$1次  
for (( i=$1;i>=1;i-- ));do
#通过$RANDOM获取随机数,并通过取余数获取到数组下标0~n内的一个元素
        ran=`echo "$RANDOM % $new_name_c" | bc`
#每输出一个,则删除当前对应数组元素,并便于下次判定是否为空,若为空,则说明与上次获取一致
        if [ -n "${name[$ran]}" ];then
                echo -n "${name[$ran]} "
                unset name[$ran]
        else
#若为空,则i加1,即本次循环获取失败,不至于少获取一个
        let i++
        fi
done
 

相关内容

    暂无相关文章