引語:我本人以前并沒有寫過shell腳本,也許是因為懶,也許是沒有被逼到要去寫shell的地步。但是,前段時間,工作需求,要求重新跑幾個月的腳本,這些腳本是每天定時進行跑的,而且每天是好幾個腳本一起關聯跑的。你也許會說,這太簡單了,寫個循環,然后,讓他自己去跑就行了。是的,你可以很順手的用你的編程語言去寫循環,如PHP。但是,你知道,這樣做其實是改變了代碼結構了,鬼知道會導致什么結果呢? 并且,我并不保證里面所有代碼的意思,我都懂!那么,問題來了,在不改變原代碼的前提下,怎樣去循環這幾個月的時間呢? 沒錯,那就是,模擬真實運行時的情況,傳入需要接收的日期參數(前提是你的代碼里面已經有了這個門)!你知道,這種定時腳本都有一個優雅的名字,crontab,那么,就是shell了,你要做的就是寫shell了。
沒有寫過shell? 沒關系了,其實需求確定之后,你顯然已經知道,這太簡單了。不就是語法問題嗎? 你別告訴我你不會谷歌,不會百度!
我就先拋幾個需要考慮的點,后面直接給代碼吧!
1、怎樣獲取當前時間,并轉換成你需要的格式? 關鍵詞: date
2、怎樣防止同時多次運行同一個內容? 關鍵詞: lock
3、怎樣讓程序運行完一次之后,冷卻執行? 關鍵詞: sleep
4、怎樣指定運行時間段,counter或者起始日期? 關鍵詞: while, let, expr
5、附加:怎樣知道當前的運行狀態如何了? 關鍵詞: echo , progress
把這些問題考慮好了,你就一步步去寫吧,不知道語法的,直接谷歌、百度,代碼參考如下:
#/bin/bash# @author: youge# @date: 2015-12-22startDate="2015-11-24"    # when to start startDateTimestamp=`date -d "$startDate" +%s`endDate="2015-12-14"      # when to endendDateTimestamp=`date -d "$endDate" +%s`sleepTime=25        # to take a breakhaveSthUndo=0      # check if there is something undo , if not , exit the programrootDir='/cygdrive/d/wamp/ppi/'dir=$rootDir"cron/"itemArr=("itemA" "itemB" "itemC")  # the items you want to run therefor item in ${itemArr[@]}do  runFile=$rootDir$item".run";  if [ ! -f "$runFile" ] ; then  haveSthUndo=1;  echo $item" runs on me" $runFile " touched";  echo -e "script startTime: "`date "+%Y-%m-%d %H:%M:%S"` "/nbeginDate:" $startDate "/nendDate:" $endDate "/npath:" $dir >> $runFile  touch "$runFile";  break;  else  echo $item "is runing, skipped. " $runFile;  fidone;if [ $haveSthUndo -ne 1 ]; then  echo -e "Nothing to do now .../ncheck it...";  exit;fiecho "haveSthUndo eq: " $haveSthUndo;while [[ $endDateTimestamp -ge $startDateTimestamp ]]do  runDate=`date -d @$startDateTimestamp +%Y-%m-%d`;    #1987-01-06  params="item=$item&d=$runDate";  msg="[`date "+%Y-%m-%d %H:%M:%S"`] now we run the date: "${runDate}" [params]: "${params};  echo $msg;          # to show me ...  echo $msg >> $runFile;  # run the scripts below  cd $dir &&    /bin/php ./script1.php $params &&    /bin/php ./script2.php $params &&        /bin/php ./scriptx.php $params  # run the scripts upon  startDateTimestamp=`expr $startDateTimestamp + 86400`;    # run the next day ...  echo " ___sleeping for $sleepTime seconds ... ";  x='';  for ((itime=0; itime<$sleepTime; itime++)); do    let itime2=$itime+1;    progress=`expr $itime2 /* 100 / $sleepTime`;    printf "cooling:[%-"$sleepTime"s]%d%%/r" $x $progress    x=#$x    sleep 1;              # sleep xx seconds to run the next time, show the progress  done;  echo;done;echo "[`date "+%Y-%m-%d %H:%M:%S"`] the end." >> $runFile;#end of the file            
新聞熱點
疑難解答