Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set Cron Job for 1st working day of every month in Shell Scripting

Tags:

linux

shell

unix

I'm new to scripting language, can anyone please explain how to set the cron job for 1st working day?

like image 294
Shirchabayshan Avatar asked Oct 18 '25 04:10

Shirchabayshan


2 Answers

You can use the following,

@monthly    

Run once a month at the morning of the first day of the month.

0 0 1 * * /home/scripts/your_script_file.sh

3rd Edit:

This will run your job at morning say 10 AM on the first weekday of the month:

# First weekday of the month

# Monday - Friday
00 10 1-3 * * [ "$(date '+\%a')" == "Mon" ] && /home/scripts/your_script_file.sh
00 10 1 * * [ "$(date '+\%a')" == "Tue" ] && /home/scripts/your_script_file.sh
00 10 1 * * [ "$(date '+\%a')" == "Wed" ] && /home/scripts/your_script_file.sh
00 10 1 * * [ "$(date '+\%a')" == "Thu" ] && /home/scripts/your_script_file.sh
00 10 1 * * [ "$(date '+\%a')" == "Fri" ] && /home/scripts/your_script_file.sh
like image 122
Skynet Avatar answered Oct 20 '25 19:10

Skynet


First, run the date command:

$ date '+%x'
> 12/29/2014

%x tells date to display today's date in the format of the current locale. Using that exact same format, put a list of holidays in a file called holidays. For example:

$ cat holidays
> 01/01/2015
> 07/04/2015

Next, create the following shell script:

#!/bin/sh
dom=$(date '+%d') # 01-31, day of month
year=$(date '+%Y') # four-digit year
month=$(date '+%m') # two-digit month

nworkdays=0
for d in $(seq 1 $dom)
do
    today=$(date -d "$year-$month-$d" '+%x') # locale's date representation (e.g. 12/31/99)
    dow=$(date -d "$year-$month-$d" '+%u')   # day of week: 1-7 with 1=Monday, 7=Sunday
    if [ "$dow" -le 5 ]  && grep -vq "$today" /path/holidays
    then
        workday=Yes
        nworkdays=$((nworkdays+1))
    else
        workday=
    fi
done
[ "$workday" ] && [ "$nworkdays" -eq 1 ] && /path/command
like image 45
Shirchabayshan Avatar answered Oct 20 '25 17:10

Shirchabayshan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!