How to Get Last Day of Month in Bash


You can use the following syntax to get the last day of the current month in Bash:

date -d "-$(date +%d) days month" +%Y-%m-%d

Here is how this syntax works:

  • The inner date +%d returns the current day of the month.
  • By using a negative sign ( – ) in front of date +%d, we subtract this number of days from the current date, which is equal to the last day of the previous month.
  • Then, by using month we are able to add one month to get the last day of the current month.
  • Lastly, we use +%Y-%m-%d to format the resulting date in a specific format with the year, month and day concatenated together using dashes.

The following example shows how to use this syntax in practice.

Example: Get Last Day of Current Month in Bash

This article is currently being written on 7/22/2024.

We can use the following syntax to get the last day of the current month in Bash:

date -d "-$(date +%d) days month" +%Y-%m-%d

The following screenshot shows how to use this syntax in practice:

Bash get last day of month

This returns 2024-07-31, which is the last day of the current month in a %Y-%m-%d format.

Note that you can specify any date format that you’d like.

For example, you could use the following syntax to instead return the last day of the current month in a %m/%d%Y format instead:

date -d "-$(date +%d) days month" +%m/%d/%Y 

The following screenshot shows how to use this syntax in practice:

Bash get last day of current month in specific format

This returns 07/31/2024, which represents the last day of the current month in a %m/%d%Y format.

Feel free to specify any date format that you would like.

Related Tutorials

The following tutorials explain how to perform other common tasks in Bash:

Bash: How to Get Month Name
Bash: How to Get Day of Week
Bash: How to Compare Dates
Bash: How to Extract Date from String

Leave a Reply