19

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?

5
  • Are you limiting yourself to only bash?
    – jedwards
    Sep 12, 2012 at 5:12
  • @jedwards I am open to other bash but must be in unix / linux
    – Jack
    Sep 12, 2012 at 5:28
  • 1
    Why the restrictions? Is thia homework? Sep 12, 2012 at 6:03
  • 1
    @KeithThompson Nope, this is not a homework. I am more interested in optimize speed and using lesser command to accomplish tasks and was wondering if bash can get the last day of a month without telling bash to go through a loop (e.g. if a certain month value, then display this value) or performing hard-coding.
    – Jack
    Sep 12, 2012 at 6:58
  • 3
    If speed optimization is your concern, then I suggest saying so rather than imposing specific restrictions. If speed is that important, a C program would probably be a better choice. Sep 12, 2012 at 8:49

13 Answers 13

53

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.

6
  • Very nice, only one call to date, beats mine!
    – amdn
    Sep 12, 2012 at 13:12
  • 1
    @amdn: this may be better code, but without your explanation (below), I'd have no clue what this is doing :-)
    – TomRoche
    Jun 18, 2013 at 20:41
  • 1
    ... at the cost of comprehension. Mar 31, 2016 at 15:32
  • 3
    ah, yes, comprehension: I first thought $m/1 was a division, but it's actually the base date for the calculation. I added the year, so it's more flexible and maybe less confusing: y=2000; m=2; date --date="$y/$m/1 + 1 month - 1 day" "+%b %Y - %d days";
    – rudi
    Feb 21, 2018 at 16:44
  • 2
    Like several of the other answers here, this requires GNU date, which is generally not the version installed on non-Linux systems.
    – tripleee
    Dec 23, 2019 at 13:05
20
cat <<EOF
Jan - 31 days
Feb - `date -d "yesterday 3/1" +"%d"` days
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
EOF
1
  • 4
    I want to upvote you and downvote you at the same time ;) (I settled on the upvote) Sep 3, 2014 at 9:12
8
cal $(date +"%m %Y") |
awk 'NF {DAYS = $NF}; END {print DAYS}'

This uses the standard cal utility to display the specified month, then runs a simple Awk script to pull out just the last day's number.

3
  • 2
    While this code snippet may solve the question, including an explanation really helps to improve the quality of your post. Remember that you are answering the question for readers in the future, and those people might not know the reasons for your code suggestion.
    – Paul Roub
    Apr 8, 2016 at 21:55
  • 1
    The Awk script could be simplified to just 'END { print $NF }'
    – tripleee
    Dec 23, 2019 at 13:20
  • I would like to use this, but the last line is always empty, so $NF gives no output.
    – saulius2
    Jun 30, 2020 at 8:14
7

Assuming you allow "for", then the following in bash

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

produces this

 Jan - 31 days
 Feb - 29 days
 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

Note: I removed the need for cal

For those that enjoy trivia:

Number months from 1 to 12 and look at the binary representation in four
bits {b3,b2,b1,b0}.  A month has 31 days if and only if b3 differs from b0.
All other months have 30 days except for February.

So with the exception of February this works:

for m in {1..12}; do
    echo $(date -d $m/1/1 +%b) - $((30+($m>>3^$m&1))) days
done

Result:

Jan - 31 days
Feb - 30 days (wrong)
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
3
  • I'm running Linux, "which cal" responds /usr/bin/cal
    – amdn
    Sep 12, 2012 at 5:31
  • I know why, cal was not installed in my machine.
    – Jack
    Sep 12, 2012 at 5:32
  • I modified my answer so it doesn't need cal. Still not as straightforward as clyfish's answer.
    – amdn
    Sep 12, 2012 at 6:04
5

Try using this code

date -d "-$(date +%d) days  month" +%Y-%m-%d
1
  • 3
    The inner date +%d call returns the current day of this month. The value for the -d flag becomes (for example): "-8 days month", which, according to the docs means "subtract 8 days from the current date and add one month". Subtracting the current number of days takes you back to the end of the previous month, and adding one month takes you to the end of the current month. GNU date also has a --debug switch which can help to explain what's happening.
    – simpsora
    May 8, 2019 at 0:02
5

Returns the number of days in the month compensating for February changes in leap years without looping, using an if statement or forking to a binary.

This code tests date to see if Feb 29th of the requested year is valid, if so then it updates the second character in the day offset string. The month argument selects the respective substring and adds the month difference to 28.

function daysin()
{
   s=303232332323                                        # normal year
   ((!($2%4)&&($2%100||!($2%400)))) && s=313232332323      # leap year
   echo $[ ${s:$[$1-1]:1} + 28 ]
}

daysin $1 $2                                               #daysin [1-12] [YYYY]
2
  • With code also add some details how this answer help OP or other to fix current issue. Jan 8, 2016 at 1:24
  • Note: your comments # leap year and # normal need to be swapped to be associated with the correct line. s="303232332323" is the normal month encoding for the addition in the echo line. Jan 8, 2016 at 6:17
4

On a Mac which features BSD date you can just do:

for i in {2..12}; do date -v1d -v"$i"m -v-1d "+%d"; done

Quick Explanation

-v stands for adjust. We are adjusting the date to:

-v1d stands for first day of the month

-v"$i"m defined the month e.g. (-v2m for Feb)

-v-1d minus one day (so we're getting the last day of the previous month)

"+%d" print the day of the month

for i in {2..12}; do date -v1d -v"$i"m -v-1d "+%d"; done
31
28
31
30
31
30
31
31
30
31
30

You can add year of course. See examples in the manpage (link above).

2
  • 2
    Nice solution but it doesn't show December does it?
    – Dan
    Jun 27, 2018 at 18:28
  • Good catch. No it does not :-)
    – patm
    Jun 28, 2018 at 21:19
1

Contents of script.sh:

#!/bin/bash
begin="-$(date +'%-m') + 2"
end="10+$begin"

for ((i=$begin; i<=$end; i++)); do
    echo $(date -d "$i month -$(date +%d) days" | awk '{ printf "%s - %s days", $2, $3 }')
done

Results:

Jan - 31 days
Feb - 29 days
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
1
  • @Jack: Thanks, yes end="10+$begin" should actually be end="11+$begin". Glad you chose Glenn's answer, it is far superior.
    – Steve
    Sep 14, 2012 at 0:49
1

Building on patm's answer using BSD date for macOS (patm's answer left out December):

for i in {1..12}; do date -v1m -v1d -v+"$i"m -v-1d "+%b - %d days"; done
Explanation:

-v, when using BSD date, means adjust date to:

-v1m means go to first month (January of current year).

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

"+%b - %d days" is whatever format you want the output to be in.

This will output all the months of the current year and the number of days in each month. The output below is for the as-of-now current year 2022:

Jan - 31 days
Feb - 28 days
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
0
for m in $(seq 1 12); do cal  $(date +"$m %Y") | grep -v "^$" |tail -1|grep -o "..$"; done
  • iterate from 1 to 12 (for...)
  • print calendar table for each month (cal...)
  • remove empty lines from output (grep -v...)
  • print last number in the table (tail...)

There is no sense, to avoid using cal, because it is required by POSIX, so should be there

0

A variation for the accepted answer to show the use of "yesterday"

$ for m in {1..12}; do date -d "yesterday $m/1 + 1 month" "+%b - %d days"; done
Jan - 31 days
Feb - 28 days
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 it works?

Show the date of yesterday for the date "month/1" after adding 1 month

0

I needed this few times, so when in PHP comes with easy in bash is not, so I used this till throw me error "invalid arithemtic operator" and even with warrings in spellcheck ( "mt" stands for month, "yr" for year )

last=$(echo $(cal ${mt} ${yr}) | awk '{print $NF}')

so this works fine...

### get last day of month
#
# implement from PHP
# src: https://www.php.net/manual/en/function.cal-days-in-month.php
#
if [ $mt -eq 2 ];then
    if [[ $(bc <<< "${yr} % 4") -gt 0 ]];then
        last=28
    else
        if [[ $(bc <<< "${yr} % 100") -gt 0 ]];then
            last=29
        else
            [[ $(bc <<< "${yr} % 400") -gt 0 ]] && last=28 || last=29
        fi
    fi
else
    [[ $(bc <<< "(${mt}-1) % 7 % 2") -gt 0 ]] && last=30 || last=31
fi
0

Following the same answer of glenn jackman, but with an update; his answer originally used the "+ 1 month - 1 day" configuration, however I've attempted his code but it didn't work properly - for some unknown reason, my date command returned the date + 29 days (in my test event, it was a December date and it returned Dec 30, instead of Dec 31).

My recommendation is that you switch the "1 month" for "next month", which will return the correct results properly.

In my case, I had to collect from another variable the year and month, and so it ended up like this:

date -d "$AnalysisYear-$AnalysisMonth-01 00:00:00 + next month - 1 second" "+%d"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.