Setup crontab to run command on the last day of every month or first day of every month

crontab scheduleYou’re know, Crontab will not work on a specific day of the month but it can be a specific minute, hour, month and day of the week. So, if you need to run some command in the first day of month or last day of month you can’t use crontab to scheduled it. However, you can use crontab with shell script to filter out a particular date that you need to run the command.

Example script to run on last day of the month

  1. Create lastdayofmonth.sh via terminal by running
    [root@Ezylinux ~]# vi /root/lastdayofmonth.sh
    #!/bin/bash
    TODAY=`/bin/date +%d`
    TOMORROW=`/bin/date +%d -d "1 day"`
    
    # See if tomorrow's day is less than today's
    if [ $TOMORROW -lt $TODAY ]; then
            COMMAND HERE
    fi
    exit 1
    
  2. Add schedule for this script
    [root@Ezylinux ~]# crontab -e
    1 0 * * * /root/lastdayofmonth.sh 
    

Example script to run on first day of the month

  1. Create 1stdayofmonth.sh file by running
    [root@Ezylinux ~]# vi /root/1stdayofmonth.sh
    #!/bin/bash
    TODAY=`/bin/date +%d`
    YESTERDAY=`/bin/date +%d -d "-1 day"`
    
    # See if tomorrow's day is less than today's
    if [ $TODAY -lt $YESTERDAY ]; then
            COMMAND HERE
    fi
    exit 1
    
  2. Add schedule for this script
    [root@Ezylinux ~]# crontab -e
    1 0 * * * /root/1stdayofmonth.sh 
    
Incoming search terms: cron last day of month
You can leave a response, or trackback from your own site.

Leave a Reply

*