How to set up and use rsync with cron for automated backups?

Published on Aug. 22, 2023, 12:18 p.m.

To set up and use rsync with cron for automated backups, you can create a shell script that contains the rsync command to transfer the files, and then add a cron job to run the script at scheduled intervals. Here are the steps to follow:

  1. Create a new shell script with your rsync command. For example:
#!/bin/bash
rsync -avz /path/to/local/dir user@remote:/path/to/remote/dir

This script specifies the source directory (/path/to/local/dir), the destination directory on the remote machine (user@remote:/path/to/remote/dir), and uses the same avz options as the previous command.

  1. Save the script to a location on your Linux machine, such as /home/user/scripts/mysync.sh.
  2. Make the shell script executable with the following command:
chmod +x /home/user/scripts/mysync.sh
  1. Open the crontab editor with the following command:
crontab -e
  1. Add the following line to the crontab file to schedule the rsync command to run at midnight every day:
0 0 * * * /home/user/scripts/mysync.sh
  1. Save and exit the crontab editor.

The above example schedules the script to run at midnight every day. Modify the cron job to suit your specific scheduling requirements. Note that if you want to receive email alerts of the cron job’s output, you can append >> /home/user/cron.log 2>&1 to the end of the command line.

Once you have set up the cron job, it will run automatically at the scheduled interval and backup the specified directories using rsync.

Tags: