shell脚本练习(随机取名)
2013-10-18 17:45
465 查看
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
相关文章推荐
- 实战Linux Shell 编程与服务器管理
- php调用shell脚本--126错误
- Linux shell编程 10 ---- 循环结构
- shell 脚本过滤段落内容
- shell_join 连接
- bash 的环境配置文件
- shell_cut 提取
- shell_sed 文件内容操作
- SCSF - Part 1 Modules and Shells
- HBASE shell 常用命令大全
- HBASE shell 常用命令大全
- SarePoint Powershell Add user to Group
- Shell Wget
- php利用root权限执行shell脚本(二)
- linux shell基础1.2--终端打印
- Linux shell编程 9 ---- 判断+运算符
- Xshell显示中文乱码问题
- uva 10152 ShellSort
- shell 删除重复行
- linux shell 基础篇1.1