Reputation: 495
I would like to run a bash script that runs every day and checks the current date to see if it is the second to last day of the month and if it is do certain things.
Upvotes: 2
Views: 1423
Reputation: 947
If you don't have GNU date you could do something like:
set -- $(date "+%d %m %Y")
cal ${2} ${3} | nawk '{NF&&n=($NF-2)};END{exit(n==d)?0:1}' d=${1}
((!$?)) && echo "do certain things"
Upvotes: 0
Reputation: 10149
You can do it with this invocation:
date --date="$(date --date "next month" +'%Y-%m-01') -2 days"
Lets analyse the pieces:
date --date="$MAGIC -2 days"
if instead of $MAGIC
we could get the first day of the next month, GNU date --date
feature would help us: try it with date --date="2016-08-01 -2 days"
$MAGIC
we use what is returned by date --date "next month" +'%Y-%m-01'
: this gives us the first of the next month, again using the --date
option of GNU date$( ... )
Upvotes: 1
Reputation: 246799
Using GNU date
today=$(date +%Y-%m-%d)
next_to_last=$( date -d "$(date +%Y-%m-01) + 1 month - 2 days" +%Y-%m-%d )
if [[ $today == $next_to_last ]]; then
echo "it is the 2nd last day of the month"
fi
The "inner" date call returns the current year and month and we hardcode "01" for the day => the first day of this month. We add 1 month, then subtract 2 days.
Upvotes: 3