这里有个需求,按月查询,而且要输出每个月的开始日期,结束日期。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