Wednesday, June 29, 2011

GET FIRST AND LAST DAY OF A MONTH IN BASH SHELL

GET FIRST AND LAST DAY OF A MONTH IN BASH SHELL




Linux system comes with a date commend. The man page has all the details. The following shows how to get the first date and last day of a month using the date commends in bash shell.

First Day, current month:
# date -d "-0 month -$(($(date +%d)-1)) days"

First Day, last month:
# date -d "-1 month -$(($(date +%d)-1)) days"

Last Day, current month:
# date -d "-$(date +%d) days +1 month"

Last Day, last month:
# date -d "-$(date +%d) days -0 month"

Last Day, month before last month:
# date -d "-$(date +%d) days -1 month"

%d = day of month.


8 comments:

Anonymous said...

Thank you, this came in handy

Arun said...

Thanks man i got it

Anonymous said...

hi community,

i therefore got an issue.
i´d like to integrate this codeline in perl:
date -d "-0 month -$(($(date +%d)-1)) days"

any suggestions?

marc

Unknown said...

Thanks dude .. it helped me a lot ... cheers for sharing !!!

Ashish said...

Best Way Thanks A lot For Sharing

William Desportes said...

Thank you, 10 years later after the post !

Here is for next month:

Start: date -d "+1 month -$(($(date +%d)-1)) days"
End: date -d "-$(date +%d) days +2 month"

William Desportes said...

Thank you, 10 years later after the post !

Here is for next month:

Start: date -d "+1 month -$(($(date +%d)-1)) days"
End: date -d "-$(date +%d) days +2 month"

Anonymous said...

still pretty useful, thanks.

the arithmetic exception needs to be changed to work in september: $(($(date +%-d)-1))

the - after % prevents padding with 0. if not, bash tries to calculate ((09-1)) which will fail with "bash: 09: value too great for base (error token is "09")" as 09 will be interpreted as octal notation.