shell按月循環取數


這里有個需求,按月查詢,並且要輸出每月的開始日期,結束日期。

shell腳本如下:

#!/bin/sh


echo "0個參數時, 按月執行,默認當前月份 "
echo "1個參數時, 按月執行,輸入月份格式:2019-02"
echo "2個參數時, 按月執行,輸入月份格式:2019-01 2019-02"

if [ $# = 1 ]; then
    start_month=$1
    end_month=$1
elif [ $# = 2 ]; then
    start_month=$1
    end_month=$2
elif [ $# = 0 ]; then
    start_month=`date +%Y-%m`
    end_month=`date +%Y-%m`
fi


start_sec=`date -d "${start_month}-01" +%s`
end_sec=`date -d "${end_month}-01" +%s`

while [ $start_sec -le $end_sec ]; do

    day_curr=`date -d @$start_sec +%Y-%m-%d`
    month_curr=`date -d @$start_sec +%Y-%m`

    start_date=`date -d"${month_curr}-01" "+%Y-%m-01"`      #月份開始日期
    tmp_dt=`date -d"${month_curr}-01 +1 months" "+%Y-%m-01"`   
    end_date=`date -d "${tmp_dt} -1 day" "+%Y-%m-%d"`       #月份結束日期

    echo $month_curr $start_date $end_date
    ## 這里放要處理的過程
    ## 123456

    ## 一次結束重置月份
    let start_sec=`date -d "${month_curr}-01 +1 months" +%s`

done

默認,不輸入參數時,執行結果:

輸入指定月份參數時:

輸入區間月份時:

 

這樣就完美了。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM