Automate your task or rsync backup using crontab

Create a bash script .sh containing your task

nano kim-rsync.sh

#!/bin/bash
# Action 1
sudo mkdir -p /var/www/html/backup/$(date +%Y-%m-%d)

# Action 2
sudo rsync -avhz --delete --stats --progress --exclude /backup --log-file=/home/kim/crontab/rsync-log/$(date +%Y-%m-%d).log /var/www/html/ /var/www/html/backup/$(date +%Y-%m-%d)/

# Action 3 backup fileserver incremental
sudo rsync -avhz --delete --stats --progress --log-file=/home/kim/crontab/rsync-log/rsync-$(date +%Y-%m-%d).log /media/windowsshare/ /srv/samba/share/

Make the bash script executable

chmod 770 kim-rsync.sh

Create crontab-master file containing all your tasks with desired scheduling

sudo nano crontab-master

MAILTO=your@email.com
* * * * * /path/to/your/bash/script.sh
* * * * * /home/kim/crontab/kim-rsync.sh

For crontab to send you email notification you need to have MTA.

sudo apt-get install mailutils

 To disable email notification 

* * * * * command > /dev/null 2>&1

To disable email notification but allow error email

* * * * * command > /dev/null

 

Load cron jobs from file crontab-master to run as root

sudo crontab –u username your-cronjob-name.txt

sudo crontab crontab-master

To edit or remove existing crontab

sudo crontab -e
sudo crontab -r

 

Scheduling a job in crontab

* * * * *
M H D M D
Minute Hour Day Month Dayofweek

Minute => In which minute
Hour => In which Hour
DOM => The Day Of Month
Month => In which month
DOW => The Day of Week

+---------------- minute (0 - 59)
| +------------- hour (0 - 23)
| | +---------- day of month (1 - 31)
| | | +------- month (1 - 12)
| | | | +---- day of week (0 - 6) (Sunday=0 or 7)
| | | | |
* * * * * Your command goes here

Examples

@reboot Run once, at startup
@yearly Run once in a year, similar to 0 0 1 1 *
@monthly Run once in a month, similar to 0 0 1 * *
@weekly Run once in a week, similar to 0 0 * * 0
@daily Run once in a day, similar to 0 0 * * *
@hourly Run once in an hour, similar to 0 * * * *

Run in every 10 minutes

0,10,20,30,40,50 * * * *
*/10 * * * *

Run every Thursday at 3pm

00 15 * * 4

 

Leave a Reply

Your email address will not be published. Required fields are marked *

Scroll to top