Last Updated: February 25, 2016
· deiu

Remove (prune) files from your entire Git history.

In case you forgot to remove sensitive or binary files from your Git repository, here is a quick script which aims to remove all said files from all you previous commits. You can run it like this:
sh git-delete-history file1 dir1

Gist version here.

# Script to permanently remove files/folders from your git history.  To use 
# it, cd to your repository's root and then run the script with a list of paths
# you want to delete

set -o errexit

if [ $# -eq 0 ]; then
    echo "Usage: $0 file1 file2"
    echo "   or: $0 path1 path2"
    exit 0

# make sure we're at the root of git repo by checking for a .git dir
if [ ! -d .git ]; then
    echo "Error: must run this script from the root of a git repository"
    exit 1

# remove all paths passed as arguments from the history of the repo
git filter-branch --index-filter "git rm -rf --cached --ignore-unmatch $files" HEAD

# remove the temporary history git-filter-branch otherwise leaves behind for a long time
rm -rf .git/refs/original/ && git reflog expire --all &&  git gc --aggressive --prune

2 Responses
Add your response

How safe is this script to operate? These actions are the kind of thing I would do to a new clone and force push history back upstream when I felt comfortable with the changes.

over 1 year ago ·

The script should be pretty safe. I have used it several times in the past and I've never experienced any issues so far.

over 1 year ago ·