Skip to content
shellhacks.dev
Linux

Get the last day of the month

Get the last day of a month with GNU date by adding one month to the first day and subtracting one day. Adding a month to the 31st lands in the wrong month.

1 min read
Summarize in AI

A job runs on the last day of each month, and the number of days changes with the month and with leap years.

Shell
date -d '2026-01-31 next month -1 day' +%F
d=2026-01-31
date -d "${d%-*}-01 +1 month -1 day" +%F
date -d "2028-02-01 +1 month -1 day" +%F
Text
2026-03-02
2026-01-31
2028-02-29

Adding a month to the 31st of January gives "31 February", which GNU date normalizes to the third of March, and one day before that is the second, so the first line is wrong. Starting from the first day of the month avoids that: the first of next month minus one day is always the last of this one. The date arithmetic follows the relative items rules. The last run shows the leap year, where February 2028 ends on the 29th.

GNU date only. For a cron job, test the day in the command instead: [ "$(date -d tomorrow +%d)" = 01 ] && run-the-job, since the cron time fields cannot express "last day". Remember the percent signs in a crontab need escaping.

Share

More snippets

Linux

Get a process's command line

Read a running process's full command line from /proc/PID/cmdline. The arguments are separated by NUL bytes, so split them with xargs -0 and not tr.

1 min read
Linux

Always use -a with -G

Add a user to a group with usermod -aG. Without -a the -G option replaces the whole supplementary group list, and the user silently loses every other group.

1 min read
Linux

Run a command with a clean environment

Run a command with an empty environment using env -i, then add back only the variables you pass. It reproduces what cron or a minimal container sees.

1 min read

Get new posts by email

One email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.