DEV Community

Izawa
Izawa

Posted on

Auto-Backup Your Git Repo on Every Commit

AI coding tools are great, but there's a non-zero chance one of them nukes your .git folder someday. Scheduled backups work, but I wanted something that just happens automatically β€” so I set up a bare repository on a separate drive that syncs on every commit via a post-commit hook. Here's how. (macOS, but Linux is identical.)


Step 1: Create the bare repository

Pick somewhere outside your project β€” an external drive works well.

mkdir -p /path/to/backup/project.git
cd /path/to/backup/project.git
git init --bare
Enter fullscreen mode Exit fullscreen mode

A bare repo stores only history, no working files. Same format GitHub uses internally.


Step 2: Register it as a remote

cd ~/path/to/project

git remote add backup /path/to/backup/project.git

# Initial push (check your branch name first)
git branch --show-current
git push backup <branch-name>

# Verify
git ls-remote backup
Enter fullscreen mode Exit fullscreen mode

Step 3: Add the post-commit hook

touch .git/hooks/post-commit
chmod +x .git/hooks/post-commit
Enter fullscreen mode Exit fullscreen mode

.git/hooks/post-commit:

#!/bin/sh
current_branch=$(git rev-parse --abbrev-ref HEAD)
git push backup "$current_branch" --quiet >/dev/null 2>&1 &
Enter fullscreen mode Exit fullscreen mode

The & runs it in the background so commits don't feel any slower.


Verifying it works

touch backup_test.txt
git add backup_test.txt
git commit -m "test: post-commit hook"
Enter fullscreen mode Exit fullscreen mode

Then compare hashes:

git log --oneline -1
git ls-remote backup
Enter fullscreen mode Exit fullscreen mode

If main points to the same hash in both, you're good. Clean up:

git rm backup_test.txt
git commit -m "chore: remove test file"
Enter fullscreen mode Exit fullscreen mode

Recovery

If only .git was deleted (files intact):

cd /path/to/project
git init
git remote add backup /path/to/backup/project.git
git fetch backup
git branch -r  # confirm branch name
git reset --mixed backup/<branch-name>
git status     # commit any remaining diff
Enter fullscreen mode Exit fullscreen mode

If the whole folder is gone:

git clone /path/to/backup/project.git my_project
Enter fullscreen mode Exit fullscreen mode

In both cases, re-add the post-commit hook afterward since .git/hooks/ isn't tracked by Git.


That's it. A bit of setup, but once it's running you don't think about it again.

Top comments (0)