This post will describe how to create a shell script to check a git repository status every so often to check for changes.
Why would you write something like this? Whilst Git is primarily used to version control files and improve developer’s and development team’s workflow, it can also be used as a security measure to check for any unexpected new or modified files within your repository.
There are many stories online about how malware has infected a website and the user or development teams that are responsible for the management of the site haven’t been able to pinpoint the infected files.
If you use Git as a version control system for your website, you can simply run a
git status command that will inform you of the status of your Git repository.
The shell script therefore is simple. The script simply
cd‘s into the directory of the Git repository and runs the
git status command. If there are any untracked or modified files within the directory, the script will end an email to you informing you of the new file(s) that have appeared or files that have been modified.
The code that the shell script contains might look like the below.
dir='/your/repository/directory' cd "$dir" changes=$(git status --porcelain) if [ "$changes" ]; then # Changes mail -s "Repository changes" "email@example.com" <<EOF *** CHANGES FOUND *** Directory: $dir $changes EOF fi
You can then configure the shell script to run on your server’s crontab at a specified frequency.
To do this, log onto your server and run
crontab -e, and add in the command to execute the shell script.
For example, the below code will execute the shell script every 15 minutes.
*/15 * * * * /path/to/sh /path/to/repo_check.sh
If there are any changes, you’ll be emailed with the file names that have been added or modified.
For example, the output might look like the below.
*** CHANGES FOUND*** M css/styles.scss ?? text.txt
When you create a shell script to check a git repository status, you’ll have an extra security check to ensure that any malicious or unexpected code that might find in your repository gets cleared as soon as possible.
You’ll need to make sure your
.gitignore file contains the relevant directories and files to ignore, otherwise you might be falsely notified about changes to the repository.
You might encounter this if your repository contains a website that allows the uploading of images in the website’s CMS. Since the images are directly uploaded on the server and not through Git, make sure any file upload directories and other relevant areas of your repository are added to