cal without any further parameters prints the current month in 4 - 5 lines plus two header lines. In these lines, the awk searches for today and, if found, prints $2, the second field, which is Monday as the weeks in cal start with Sunday.
date 's %u format specifier supplies the day-of-week of the first day in the target month, which then is subtracted from 16 (for second week) or 30 (4. wk, experimental values). Should the First be a Monday, subtract another 7 days.
Looks like your shell doesn't zero pad the MONTH sequence as does my bash . You may want to consider the various options that your shell offers for "brace expansion". Otherwise, prepend single digit MONTHs with a "0" by shell means.
---------- Post updated at 09:40 ---------- Previous update was at 09:39 ----------
Are you trying to determine if the script is started on the correct day, i.e. 2nd & 4th Monday only?
If so, start it every day and have a section to test the date at the top similar to this:-
date '+%d %w'|read dayofmonth dayofweek
((weekofmonth=1+$dayofmonth/7))
if [ $dayofweek -ne 1 -o \( $weekofmonth -ne 2 -a $weekofmonth -ne 4 \) ]
then
printf "Not running today.\n"
exit 0
fi
# Now able to run main script
Apologies if I have missed the point, but I hope that this helps.
... the logic is that I divide the day of the month by seven (losing any remainder) and that gives me a value between zero and four. I add the 1 to make it easier to understand when testing, i.e. 1 for first week, 2 for second week etc.
That's because the algorithm assigns day 7 to the second week already, which is the case for the second Monday of September and December, 2015. On top, the empty lines are due to invalid dates for months that dont have a 31., or 29., 30., 31. for February. And, DATE and dayofmonth hold identical values. Try the modified script:
YEAR=2015
for MONTH in $(seq -w 1 12)
do for DATE in $(seq -w 1 31)
do dayofweek=$(date -d"${YEAR}${MONTH}${DATE}" +%w)
[ $? == 0 ] || continue
weekofmonth=$(( 1 + (10#$DATE - 1) / 7 ))
if [ $dayofweek -ne 1 -o \( $weekofmonth -ne 2 -a $weekofmonth -ne 4 \) ]
then continue
else MONDAY_DATE=`date -d"${YEAR}${MONTH}${DATE}" +%d.%m.%Y`
echo "$MONDAY_DATE"
fi
done
done
Thanks RudiC.
Can you please advise how are you coming up with the value 10 in below code? Basically, I want to understand the thought process while selecting the value, so the logic will be clear and will help in long run.