歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> SHELL編程 >> shell腳本聯系(隨機取名)

shell腳本聯系(隨機取名)

日期:2017/3/1 14:02:09   编辑: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
Copyright © Linux教程網 All Rights Reserved