Reputation: 900
I'm trying to the month number of the last Monday of this week. I got it to check what day of the week it is and if it's not Monday then subtract x days and set that new date as the variable value.
What I'm having trouble with is formatting this variable to only get the month. Everything works except the 2nd to last line below.
startDate=$(date)
weekDayNum=$(date +'%u') # 1 is Monday
# If today is NOT Monday
if [ weekDayNum > 1 ];
then
# Get the date for the last Monday
newWeekDayNum=$(($weekDayNum-1))
startDate=$(date -j -v-${newWeekDayNum}d)
fi
month=$(date -d "$startDate" +'%m')
echo $month```
Upvotes: 1
Views: 7029
Reputation: 19717
[ weekDayNum > 1 ]
doesn't test for numeric order. Use [ $weekDayNum -gt 10 ]
(you also did not access the value of your weekDayNum variable).
It seems you have to supply the format string in the BSD variant of date
:
This works for me:
#!/usr/bin/env bash
LANG=C
startDate=$(date)
weekDayNum=$(date +'%u') # 1 is Monday
# If today is NOT Monday
if [ $weekDayNum -gt 1 ];
then
startDate=$(date -j -v "-$(($weekDayNum - 1))d")
fi
month=$(date -j -f "%a %b %d %T %Z %Y" "${startDate}" +'%m')
echo $month
Upvotes: 1
Reputation: 31648
Use expr
to convert it to number.
month=$(date -d "$startDate" +'%m')
month=$(expr $month + 0)
echo $month
Output:
8
Upvotes: 0