BASH Script to take backup of a folder whenever something is changed in it

BASH Script to take backup of a folder whenever something is changed in it

ยท

2 min read

Let me clarify the problem statement a little bit before we move on to solve it!

We have a directory that we need to back up periodically. But periodically here means that whenever something is added, modified, moved, or deleted from this directory the backup needs to happen!

Please note here backup simply means copying the content of the directory to some other location. So we can use the rsync utility which can handle this task very effectively. Read more about it [here.](https://www.geeksforgeeks.org/rsync-command-in-linux-with-examples/)

Now how can we watch the directory so that we can trigger backup whenever anything has changed in it? ๐Ÿค”

After spending some time on StackOverflow, I got to know about inotifywatch. It is a utility that can do just that for us! So let's install it first:

sudo apt install inotify-tools

Writing the script

Now we are ready to write our bash script, and here it is:

#!/bin/bash

################################################################################
##             WRITTEN BY - HARSHIT SHARMA <harshits908@gmail.com>            ##
## This script is going to montior a directory and backup it whenever any     ##
## change is made to this directory.                                          ##
## Two tools are used here:                                                   ##
## inotifywait (A handy utility for monitoring the folder for any event)      ##
## rsync (A utility to copy files to another location, backup basically)      ##
## BEFORE USING THIS SCRIPT MAKE SURE YOU HAVE BOTH THESE UTILITIES INSTALLED ##
################################################################################

# Provide the paths here for your use-case
originDir="/path/to/the/watched/directory/"
destinationDir="/path/to/the/destination/directory/"
logfile="/path/to/your/logfile"

# Watching the Directory using inotifywatch
inotifywait -m -r -e modify,create,delete,move "$originDir" |
while read path action file; do

        # Trigger - Change Detected
        currentTime=$(date +"%T")
        echo "Change detected in the database @ $currentTime , Making a backup!" >> "$logfile"

        # Taking the backup
        rsync -avz $originDir $destinationDir --delete >> "$logfile"

        echo "Backup Complete!" >> "$logfile"

done

Running the script

Save the script as script.sh

Give the permission to execute:

sudo chmod +x ./script.sh

Execute the script:

./script.sh

And the watches will be set!

Conclusion

So that was it for this blog! Feel free to use this script. โœ…

If you find this somewhat informative, please like this blog! โœจ

Connect with me:

๐Ÿ”— LinkedIn: linkedin.com/in/harshit-sharma--

๐Ÿ”— My YouTube Channel: youtube.com/c/CoderBuddy?sub_confirmation=1

๐Ÿ”— GitHub: github.com/harshit-sharma-gits

ย