Alexander Lallier
Alexander Lallier

Reputation: 495

Bash script, get second to last day of the current month

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

Answers (3)

Ell
Ell

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

Lars Fischer
Lars Fischer

Reputation: 10149

You can do it with this invocation:

date --date="$(date --date "next month" +'%Y-%m-01') -2 days"

Lets analyse the pieces:

  1. outer layer: 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"
  2. inner layer: instead of $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
  3. you could either use two lines or use command substitution with $( ... )

Upvotes: 1

glenn jackman
glenn jackman

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

Related Questions