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.
#!/bin/bash
# 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
fi
# 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
fi
# remove all paths passed as arguments from the history of the repo
files=$@
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
Written by Andrei Sambra
Related protips
2 Responses
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
·
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#Git
Authors
khasinski
591.1K
dmichaelavila
500.4K
Related Tags
#git
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#