bash 指令碼寫的“抓鬮程式”(隨機數)

來源:互聯網
上載者:User

剛才想著抓鬮,又懶著去找筆,就順手寫了一個抓鬮的指令碼:

使用前建立一個抓鬮項目的檔案,比如,我想以後著重研究“C/C++"、"Java"、"Python"中的一個,首先建立一個隨便什麼名字的檔案:

xiwang@ubuntu:~/Dev/DrowLots$ cat records.txtC/C++JavaPython

然後運行指令碼:

xiwang@ubuntu:~/Dev/DrowLots$ ./drowlots.sh records.txtPython

好了,我知道了,以後C/C++繼續是我的主打語言,但是多多學習Python。嗯!

指令碼的一個核心就是隨機數的問題,這裡直接用這樣的bash命令:

G_RANDOM_RETRUN=$((RANDOM % 100 + 1))    # 這樣,隨機數 1~100 就儲存在了G_RANDOM_RETURN環境變數裡邊了。

指令碼如下:

#!/bin/bash# drowlots.sh, 2012-06-16 T2129## @param $1  - A file contains all the items, ONE RECORD PER LINE.#NAME="drowlots.sh"; export NAMEVERSION="2012-06-16 T2129"; export VERSIONcd $(dirname $0)WORKDIR=$PWDtest ! -z "$1" && test -f "$1" || {  echo "Need a input file, which includes records in lines"  exit 1}RECORD_FILE="$1"# get a random# @param $1  - get radom number from 1 to $1# return $G_RANDOM_RETRUN, the random number.random() {  test ! -z "$1" && test "$1" -ge 1 || {    return 1  }  G_RANDOM_RETRUN=$((RANDOM % $1 + 1)); export G_RANDOM_RETRUN  return 0}sed '/^[[:blank:]]*$/d' -i $RECORD_FILErandom $(wc -l $RECORD_FILE) || {  echo "random's param should be >= 1"}sed -n "$G_RANDOM_RETRUN {p}" $RECORD_FILE

下邊的實現,是多人的情況下一人一鬮的玩法,而不是自己抓著玩:

需求是這樣的,一人抓一次,用同一個資料檔案,知道抓完為止,上次實現就變成

$./drowlots.sh records.txt    #<! 第一個人抓鬮,拿到了JavaJava$./drowlots.sh records.txt    #<! 第二個人抓鬮,拿到了C/C++C/C++$./drowlots.sh records.txt    #<! 第三個人抓鬮,拿到了PythonPythonNo drow lost left

具體指令碼實現:

#!/bin/bash# drowlots.sh, 2012-06-17 T0953## @param $1  - A file contains all the items, ONE RECORD PER LINE.#NAME="drowlots.sh"; export NAMEVERSION="2012-06-17 T0953"; export VERSIONtest ! -z "$1" && test -f "$1" || {  echo "Need a input file, which includes records in lines"  exit 1}# $RECORD_FILE is a copy of $1, and used for processing runtime.RECORD_FILE="$1.$(date +"drowlots")"test -f $RECORD_FILE || {  cp "$1" "$RECORD_FILE"}# get a random# @param $1  - get radom number from 1 to $1# return $G_RANDOM_RETRUN, the random number.random() {  test ! -z "$1" && test "$1" -ge 1 || {    return 1  }  G_RANDOM_RETRUN=$((RANDOM % $1 + 1)); export G_RANDOM_RETRUN  return 0}sed '/^[[:blank:]]*$/d' -i $RECORD_FILErandom $(cat $RECORD_FILE | wc -l)sed -n "$G_RANDOM_RETRUN {p}" $RECORD_FILEsed "$G_RANDOM_RETRUN {d}" -i $RECORD_FILE# remove $RECORD_FILEtest $(cat $RECORD_FILE | wc -l) -ge 1 || {  echo "No drow lost left"  rm -f $RECORD_FILE}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.