Reputation: 43
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?
Upvotes: 0
Views: 238
Reputation: 21955
if [ "$Day" -lt "15" ] # No harm double quoting $Day, note this is integer comparison
then
(( Output_Month = Month - 1 )) #You may omit $ inside ((..)) construct
fi
Upvotes: 0
Reputation: 386
The date command is quite smart, you can just write:
if [ $Day -lt 15 ]; then
Output_Month=$(date -d "-1 month" +%m)
fi
Upvotes: 2
Reputation: 121357
First of all, you have typo: It's if
(lowercase), not If
.
To do arithmetic, you can use the $((..))
construct. So, it could be written as:
Month=`date +%-m`
Day=`date +%d`
if [ $Day -lt 15 ]
then
Output_Month=$((Month - 1))
fi
Also, note that I used the -
in calculating the Month
. It's because date +%d
prints with a leading 0
and any number with a leading is an octal number. So, when you have Month
as 08
or 09
then it'll be an error.
Using the -
suppresses the leading 0
.
Upvotes: 2
Reputation: 21620
Let is a bit picky about spaces before and after arithmetic operators. This should help you get your answer:
#!/bin/ksh
Month=`date +%m`
Day=`date +%d`
if [ $Day -lt 15 ]
then
let Output_Month=$Month-1
echo $Output_Month
else
let Output_Month=$Month+1
echo $Output_Month
fi
I added the control block for testing because today is obviously above the target date of 15. It is the 27th so to get any output I had to populate the else clause.
Upvotes: 0