• Uncategorized

About linux : How-I-can-get-the-next-month-in-shell

Question Detail

I would like to get the current and next months using shell script, I have tried this command:

$ date '+%b'

mar

$ date +"%B %Y" --date="$(date +%Y-%m-15) next month"

March 2018

But it always displays only the current month.

Could you please help me if there is something wrong with the commands.

Question Answer

$ date -d "next month" '+%B %Y'
April 2018

Check this post about specific caveats

Note: your command works just fine for me (archlinux, bash4, date GNU coreutils 8.29)

I wouldn’t rely on date alone to do this. Instead, perform a little basic math on the month number.

this_month=$(date +%-m)  # GNU extension to avoid leading 0
next_month=$(( this_month % 12 + 1 ))
next_month_name=$(date +%B --date "2018-$next_month-1")

Since you are using bash, you don’t need to use date at all to get the current month; the built-in printf can call the underlying date/time routines itself, saving a fork.

$ printf -v this_month '%(%-m)T\n'
$ echo $this_month
3 

What variant and version of date are you running? “Solaris 5.2” was never released, though SunOS 5.2 was a kernel in Solaris 2.2 (EOL in 1999). See the Solaris OS version history. The Solaris 10 (SunOS 5.10) man page for date does not support GNU’s --date= syntax used in the question, so I’m guessing you’re using some version of date from GNU coreutils.

Here’s a solution using BSD date (note, this is academic in the face of BSD’s date -v 1m):

date -jf %s $((1728000+$(date -jf %Y-%m-%d $(date +%Y-%m-15) +%s))) +"%B %Y"

There are three date calls here. BSD’s date allows specifying a format (GNU can intuit most formats on its own). The parent call is the one that takes the final time (as seconds since the 1970 epoch), expressing it in the desired “Month Year” format. Seconds are determine by adding 20 days to the epoch time of the current month on the 15th day. Since no month has 15+20 days, this is always the following month.

Here’s a direct translation of that logic to GNU date:

date +"%B %Y" --date="@$((1728000+$(date +%s --date=$(date +%Y-%m-15))))"

Here’s a simpler solution using GNU date, with one fewer date call:

date +"%B %Y" --date="$(date +%Y-%m-15) 20 days"

(A bug in GNU date will give you the wrong month if you run date --date="next month" on the 31st.)

The below one works in Red Hat 4.4.7-23, Linux version 2.6.32-754.2.1.el6.x86_64.
Just use the “month” for future months and “month ago” for previous months.. Dont confuse with adding +/- signs to the number. Check out.

> date "+%B-%Y"  #current month
November-2018
> date -d" 1 month" "+%B-%Y"
December-2018
> date -d" 1 month ago" "+%B-%Y"
October-2018
> 

More..

> date -d" 7 month ago" "+%B-%Y"
April-2018
>  date -d" 7 month " "+%B-%Y"
June-2019
> 

You may also like...

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.