user6645814 user6645814 - 4 months ago 12
Bash Question

Shell - Subtracting an integer from a date

I am trying to subtract an integer from a date. Basically I am trying to say that if it is the before the 15th of the month, so subtract 1 from the month. So if the day is 05-05-2016 I want to use 04 as the month.

Month=`date +%m`
Day=`date +%d`

If [ $Day -lt 15 ]
then
Output_Month=$Month - 1
fi


This does not seem to be working because I assume they are in two different formats (date and integer). How can I either subtract a month or convert the month into an integer?

Answer

The date command is quite smart, you can just write:

if [ $Day -lt 15 ]; then
    Output_Month=$(date -d "-1 month" +%m)
fi