Scripting and Automating rsync with *nix

Once you've sorted out the rsync command and run the initial backup, you need only to put the rsync command into a script and automate it with cron. To do that, you just need a text editor like Vi/Vim, Emacs or Pico.

Simply copy the rsync command(s) you used into the text editor and save it to /backups with a descriptive name. Just remember:

  • You don't need to use sudo in the script.
  • Make sure you've removed the --dry-run argument from the rsync command.
  • When saving your script, don't use s p a c e s in the file name. Use-hyphens-, _under_scores or CamelCase.
  • Give your script the .sh extension (it's a shell script).

Here's what a sample script might look like:


# Daily Data Backup
rsync -avz -e "ssh -i /backup/ssh_key" /home

Once the script is saved, you need to make it executable with chmod +x file. For example:

chmod +x /backup/

If you have gotten this far and it still looks like Klingon to you: .

Automating the rsync Script with cron

Once you have your backup script created and saved, you need only to add a cron job to automate it. To automate a cron job for your script:

  1. At terminal, add a cron job for the superuser:

    sudo crontab -e

  2. Enter the daily schedule command for

    For example, to run every night at 11:42 PM, you would enter:

    42 23 * * * /backup/

    • What are the crontab fields? »
    • « Hide this

    The fields in crontab (separated by s p a c e s or tabs) are:

    [minute] [hour] [day of month] [month] [weekday] [command] [command args]
    Use commas to designate a more than one value: 00,09,11,22
    Use hyphens to designate a range of values: 0-6

  3. Save your crontab file and close your text editor. You're all set!

Should you have questions or need help: