0

Edit: I managed to solve this myself, I actually deleted my original question as I was over complicating the process slightly, but have since answered it in case others find it useful. RegExp is not required in this case, as its dealing with mainly numeric based results.

Original question:

I have a write_cronjob() function that checks if the passed job already exists or writes to crontab if the grep condition doesn't find anything matching already.

Due to certain network restrictions cronjobs should only be scheduled in a certain window. As the schedule can be set by the user freely the script needs to detect any jobs that attempted to be scheduled outside the defined window, simply because they won't run.

The function takes two parameters:

  • $1 - contains just cron schedule e.g. 0 19 * * 3
  • $2 - contains the job/command to run

They are then merged just before the write operation if required.

Cron schedule rules must be within following criteria:

  • Monday - Friday (Weekdays)
  • 7 AM (07:00 AM) - 10 PM (22:00 PM)

I was thinking of doing range check on the day part which is simple enough, but the hour part is a bit harder, with the use of 24hr time i.e. 22 = 10 PM.

What I require is:

  1. Ability to split $1 to pick out the hour and day parts of the cronjob for conditional checks.
  2. RegExp pattern/range check on the split parts to detect if they are outside the criteria, and exit 1 accordingly.

Notes:

My shell is ash (BusyBox), I can't use an array.

0

I was able to split $1 and pull out the hour and day part with awk. As its default delimiter is white space, this splits down the cronjob time value nicely.

Example value of $1: 0 19 * * 1-5

CRONJOB_HOUR=$(echo "$1" | awk '{ print $2 }') # Second position: 19
CRONJOB_DAY=$(echo "$1" | awk '{ print $5 }') # Fifth position: 1-5

With these parts in a variable I can then do conditional checks.

The first check would be a less than or greater than check to create a range

if [ "${CRONJOB_HOUR}" -lt 7 ] || [ "${CRONJOB_HOUR}" -gt 22 ] ; then
    echo "Cronjob cannot be scheduled within specified hour"
    exit 1
fi

The second conditional is done on a match basis rather than equals, to catch values likes 1-6

if [[ "${CRONJOB_DAY}" == *"6"* ]] || 
[[ "${CRONJOB_DAY}" == *"7"* ]] 
then
    echo "Cronjob cannot be set to run at weekends"  
    exit 1
fi

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Not the answer you're looking for? Browse other questions tagged or ask your own question.