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

后端 未结 7 1670
小蘑菇
小蘑菇 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:30

    Unlike some answers, this will work for the 31st and any other day of the month. I use it to output unix timestamps but the output format is easily adjusted.

    first=$(date --date="$(date +'%Y-%m-01') - 1 month" +%s)
    last=$(date --date="$(date +'%Y-%m-01') - 1 second" +%s)
    

    Example (today's date is Feb 14, 2019):

    echo $first $last
    

    1546300800 1548979199

    To output in other formats, change final +%s to a different format such as +%Y-%m-%d or omit for default format in your locale.

    In case you need, you can also back up an arbitrary number of months like this:

        # variable must be >= 1
        monthsago=23
        date --date="$(date +'%Y-%m-01') - ${monthsago} month"
        date --date="$(date +'%Y-%m-01') - $(( ${monthsago} - 1 )) month - 1 second"
    

    Example output (today's date is Feb 15, 2019):

    Wed Mar 1 00:00:00 UTC 2017
    Fri Mar 31 23:59:59 UTC 2017

提交回复
热议问题