Linux Views 3

Automating file backups with rsync, part 1

Automating file backups with rsync, part 1 image 1

Automated backups with rsync


When you use rsync, you can keep a history of past changes and then sync the files anew.
But when there are many files, it is more efficient to check first which files have changed and then run rsync, rather than rsyncing everything.

To do that, use diff to find the differences between the two locations before rsync, and then use rsync to synchronize them.

Cases when file differences occur


  • Assumption 1: we compare a directory with a directory
  • Assumption 2: a directory may contain directories and regular files.
  • Assumption 3: directories and files that do not need to be synced are not synced.

Commands for building the script


source_path : the original path
des_path : the path to sync to

  • Check whether any files have been modified or added
    diff -r source_path des_path -q -x "*.*.*"

Command notes: -r means look at subdirectories as well, -q prints a brief result, and -x excludes files that match the regular expression in the quotes. The reason for -x is to leave rsync backup files out of the diff when you use rsync’s backup option.

  • Find modified files
    diff -r source_path des_path -q | grep "Files"

Command notes: grep Files is there because when a modified file is found, diff prints it in the form “Files 원복 백업 differ”.

Automating file backups with rsync, part 1 image 2
  • Find newly created folders

    diff -r source_path des_path -q | grep -v "des_path:" | cut -d ":" -f 1 | cut -d " " -f 3
    # check directories
    
    diff -r source_path des_path -q | grep -v "des_path:" | cut -d " " -f 4
    # check files
    

```

Command notes: when you look for newly created folders, you have to store the directory and the file separately. That is because you do not know the depth of a new directory, so you have to classify them separately and then join them. grep -v is the option that leaves out results from the backup path. The reason is that only files newly created on the original side should be saved to the backup; files created on the backup side must not be stored back onto the original.

Let’s use the above to write an automation shell script

Reactions

Comments 0

A nickname and a password are required. The same password edits or deletes the comment later. Comments appear after a review.

Comments appear after a review. The password is used again to edit or delete.