How can I get the 1st and last date of the previous month in a Bash script?

后端 未结 7 1671
小蘑菇
小蘑菇 2020-12-31 03:52

I have scheduled a Bash script to run on the 1st of the month but I need to create 2 variables in it with the 1st and last date of the previous month, whatever those may be.

7条回答
  •  甜味超标
    2020-12-31 04:29

    This can be done in two lines, tweak date format to suit.

    START_LAST_MONTH=$(date "+%F" -d "$(date +'%Y-%m-01') -1 month")
    END_LAST_MONTH=$(date "+%F" -d "$START_LAST_MONTH +1 month -1 day");
    
    #Test Code
    echo START_LAST_MONTH=$START_LAST_MONTH
    echo END_LAST_MONTH=$END_LAST_MONTH
    

    Running gives:

    START_LAST_MONTH=2018-09-01
    END_LAST_MONTH=2018-09-30
    

提交回复
热议问题