Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use bash to get the last day of each month for the current year without using if else or switch or while loop?

Tags:

bash

unix

As we know that each year have the following max day in each month as follows:

Jan - 31 days
Feb - 28 days / 29 days (leap year)
Mar - 31 days
Apr - 30 days
May - 31 days
Jun - 30 days
Jul - 31 days
Aug - 31 days
Sep - 30 days
Oct - 31 days
Nov - 30 days
Dec - 31 days

How to I get bash to return the value (last day of each month) for the current year without using if else or switch or while loop?

like image 237
Jack Avatar asked Sep 12 '12 05:09

Jack


People also ask

How do I get the last day of the month in bash?

-v1d means go to first day (so now we are in January 1). -v+"$i"m means go to next month. -v-1d means subtract one day. This gets the last day of the previous month.

What command output shows the previous month this month and the next month?

The cal/ncal commands also display the previous, current and next month surrounding today. For this, you need to pass the -3 command-line option.


1 Answers

my take:

for m in {1..12}; do
  date -d "$m/1 + 1 month - 1 day" "+%b - %d days"; 
done

To explain: for the first iteration when m=1 the -d argument is "1/1 + 1 month - 1 day" and "1/1" is interpreted as Jan 1st. So Jan 1 + 1 month - 1 day is Jan 31. Next iteration "2/1" is Feb 1st, add a month subtract a day to get Feb 28 or 29. And so on.

like image 190
glenn jackman Avatar answered Oct 24 '22 04:10

glenn jackman