Automating Backup to External Drives

Vaasudev Narayanan - Sun 05 July 2020 - scripts

I recently wrote a script to backup folders on my computer to an external disk.

  • I didn't want to back up my entire hard disk.
  • I only wanted to back up some important folders.
  • I didn't want to maintain multiple versions of the same folder.

So I wrote a simple BASH script using the rsync command to automate this process. Here is the complete script.

Read on if you are interested in a step-by-step explanation.

Assuming this is the structure of your directory.

/
    media/
        <username>/
            <Source Root Folder>/
                Folder 1/
                Folder 2/
                ...
/
    media/
        <username>/
            <Destination Root Folder>/
                Folder 1 Backup/
                Folder 2 Backup/
                ...
source_root="/media/<your-username>/<your-source-folder-root>"

destination_root="/media/<your-username>/<your-external-drive-name>/<your-destination-folder-root>"

source_root is the root directory at your computer. destination_root is the root directory at the External Drive where you want to back up.

The next few lines loop through all the folders that you want to backup. Use double quotes ("Folder 1") so that whitespaces don't give you trouble.

for folder in "Folder 1" "Folder 2" "Folder N"
do
    source_folder=$source_root/$folder/
    destination_folder=$destination_root/$folder/

This will create a new folder on the External Drive if it doesn't exist.

mkdir -p "$destination_folder"

Finally, the core of the script: rsync

rsync -rtu --delete "$source_folder" "$destination_folder"

You can go through the man-page of rsync to customize it according to your requirements.

Setup a recurring reminder in your calendar to backup. Connect your external hard drive and run the script!


Proudly powered by bootstrap, pelican, python and Alex!