2012/09/05

How to really delete a commit from Git

I really wanted to remove a huge binary file from a Git repository that has been committed by mistake. I found a bash script on the internet but the data still remained in the .git directory.

After some changes I came to this solution that really worked for me. But do not try that at home, it might corrupt your data!

#!/bin/bash
set -o errexit

if [ $# -eq 0 ]; then
    exit 0
fi

if [ ! -d .git ]; then
    echo "Error: must run this script from the root of a git repository"
    exit 1
fi

files=$@
git filter-branch --prune-empty --index-filter "git rm -rf --cached --ignore-unmatch $files" HEAD

rm -rf .git/refs/original/ && git reflog expire --expire=now --all &&  git gc --aggressive --prune=now && git repack -a -d -l
. .