Date
如何在 5 個月內執行 for 循環?
我創建了這個循環,僅在 1 個月(20170301 - 20170331)啟動我的腳本:
for ((i = 20170301; i<=20170331; i++)) ; do /home/jul/exp/prod/client/apps/scripts/runCer client-layer-name $i; done
但我希望它執行 5 個月(20170301 -20170831 之間),我該怎麼做?
假設 GNU
date
可用,您可以使用這個bash
//腳本ksh93
:zsh
start=$(date -ud 20170301 "+%s") # start time in epoch time (seconds since Jan. 1st, 1970) end=$(date -ud 20170831 "+%s") # end time for ((i=start; i <= end; i+=86400)); do # 86400 is 24 hours runCerclient-layer-name "$(date -ud "@$i" +%Y%m%d)" done
此循環執行 5*30 天,從 20170301 開始:
for (( i=0; i <= 150; ++i )); do thedate=$( date -d "20170301 + $i days" "+%Y%m%d" ) printf 'The date is "%s"\n' "$thedate" done
不過,這並沒有把我們帶到 20170831,所以……
這個從一個日期開始執行,直到我們達到一個特定的結束日期:
startdate='20170301' thedate=$startdate for (( i=0; thedate != 20170831; ++i )); do thedate=$( date -d "$startdate + $i days" "+%Y%m%d" ) printf 'The date is "%s"\n' "$thedate" done
這使用開始日期併計算從該日期起 5 個月後的結束日期,然後在那裡循環:
startdate='20170301' enddate=$( date -d "$startdate + 5 months" "+%Y%m%d" ) thedate=$startdate for (( i=0; thedate != enddate; ++i )); do thedate=$( date -d "$startdate + $i days" "+%Y%m%d" ) printf 'The date is "%s"\n' "$thedate" done
這假設 GNU
date
和一個像bash
,ksh93
或zsh
.