這裏有個需求,按月查詢,而且要輸出每個月的開始日期,結束日期。shell
shell腳本以下:spa
#!/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
默認,不輸入參數時,執行結果:code
輸入指定月份參數時:blog
輸入區間月份時:class
這樣就完美了。date