Search code examples
bashunix

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?


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?


Solution

  • 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.