3

I am trying to get the last day in this current month, or the last month, what I am using to workaround this "problem" is checking with:

if [ $DAY -eq 1 ]; then
    code here;
fi

If the day is 1, so it's saying that I am in the new month, so I need to domy backup as well.

Do you guys have any idea how can I do the check if today is the last day in the Month "January 31th" for example???

Thank you!!!!

Oracy Martos
  • 451
  • 1
  • 4
  • 19

3 Answers3

12

Getting the last day for a month is sometimes tricky, because not all months have the same days number of course.

One way to do it is to get this month's first day, add a month to that (to get next month's first day) and then subtract a day.

date --date="$(date +%Y-%m-01) +1 month -1 day"
thu jan 31 00:00:00 -07 2019

And remember that date can output whatever format you want (argument starting with +).

date --date="$(date +%Y-%m-01) +1 month -1 day" '+%F'
2019-01-31

See man date for more info or info '(coreutils) date invocation' for even more.

brunorey
  • 2,135
  • 1
  • 18
  • 26
5

One way would be to use GNU date:

if [[ $(date -d "+1 day" +%m) != $(date +%m) ]]
then
    echo "Today is the last day of the month"
else
    echo "Today is NOT the last day of the month"
fi
user000001
  • 32,226
  • 12
  • 81
  • 108
4

This gives you last day of previous month

date -d "-$(date +%d) days -0 month"

and this gives you last day of current month

date -d "-$(date +%d) days +1 month"

if [[ $(date  +%d%m%Y -d "-$(date +%d) days +1 month") != $(date +%d%m%Y) || $(date  +%d%m%Y -d "-$(date +%d) days -0 month") != $(date +%d%m%Y)  ]]
    echo "Today is NOT the last day of the month"
else
    echo "Today is the last day of the month"
fi
Derviş Kayımbaşıoğlu
  • 28,492
  • 4
  • 50
  • 72