1752608 Members
4198 Online
108788 Solutions
New Discussion юеВ

Re: scripting cron job

 
Dan Matlock_1
Regular Advisor

scripting cron job

Does anyone have a snippet of code to ID the last sunday of each month or first saturday of each month? I basically have servers that I want to reboot during those times, and need a wrapper script to launch shutdown. Bi-weekly finding even/odd week was easy, but look for creative/effective ideas on the once per month stuff.
2 REPLIES 2
A. Clay Stephenson
Acclaimed Contributor

Re: scripting cron job

I don't like the idea of rebooting like this but:

The easy way to do this is run your script each Sunday and have it decide if it is the 1st Sunday and execute or simply exit if not.

Install the attached caljd.sh in /usr/local/bin

Your script which is executed by cron every Sunday at whatever time you like looks like this:

#!/usr/bin/sh

export PATH=${PATH}:/usr/local/bin

typeset -i STAT=0
if [[ $(caljd.sh -N) -eq 1 ]]
then
echo "1st Sunday; do your thing"
# set the value of ${STAT}
fi
exit ${STAT}

---------------------------------------

The last Saturday is similar wee look at the month today and 7 days hence and if they differ, today is the last Saturday:

export PATH=${PATH}:/usr/local/bin

typeset -i STAT=0
if [[ $(caljd.sh -M) -ne $(caljd.sh -M -n 7) ]]
then
echo "Last Saturday; do your thing"
# set the value of ${STAT}
fi
exit ${STAT}

Invoke as caljd.sh -u for many examples.

If it ain't broke, I can fix that.
Muthukumar_5
Honored Contributor

Re: scripting cron job

To get last sunday of the month then,

#!/bin/sh
#sunday.sh
# /usr/bin/sunday.sh

if [[ $(date +'%d') -eq $(cal | cut -b 1,2 | grep -v '^$' | tail -1) ]]
then
# You can do reboot. It is not recommeded anway
shutdown -r now
fi

# END
exit 0
############

To execute shutdown on first saturday of the month then,

#!/bin/sh
#saturday.sh
# /usr/bin/saturday.sh

if [[ $(date +'%d') -eq $(cal | cut -b 19,20 | awk '{ if ( $1 ~ "S") { getline;print; }}') ]]
then
# You can do reboot. It is not recommeded anway
shutdown -r now
fi


# END
exit 0
############


Put this script in cron tab as,

0 7 * * * /usr/bin/sunday.sh 1>/dev/null 2>&1

it will execute every day morning 7'o clock.. And do reboot on the last sunday or saturday.

Change sunday.sh to saturday.sh to execute on first saturday.

hth.
Easy to suggest when don't know about the problem!