Skip to content

Instantly share code, notes, and snippets.

@PieterScheffers
Created January 8, 2018 15:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save PieterScheffers/47289da744446336741726b9d803fe87 to your computer and use it in GitHub Desktop.
Save PieterScheffers/47289da744446336741726b9d803fe87 to your computer and use it in GitHub Desktop.
Git - Remove pushed file or dir from git history
# Remove file/folder from history
git filter-branch -f --tree-filter 'rm -rf vendor/gems' HEAD
# or
git filter-branch --index-filter 'git rm --cached --ignore-unmatch filename' HEAD
# Run git garbage collection
git reflog expire --expire=now --all
git gc --aggressive --prune=now
# overwrite remote
git push origin --force --all
git push origin --force --tags
# (On other clients) Get new commit history
# with outstanding work (commits):
git fetch origin
git rebase
git reflog expire --expire=now --all
git gc --aggressive --prune=now
# Without outstanding work (commits):
git fetch origin
# WARNING: can destroy unpublished data!
git reset --hard origin/master
git reflog expire --expire=now --all
git gc --aggressive --prune=now
@PieterScheffers
Copy link
Author

# Make a fresh clone of YOUR_REPO
git clone YOUR_REPO
cd YOUR_REPO

# Create tracking branches of all branches
for remote in `git branch -r | grep -v /HEAD`; do git checkout --track $remote ; done

# Remove DIRECTORY_NAME from all commits, then remove the refs to the old commits
# (repeat these two commands for as many directories that you want to remove)
git filter-branch --index-filter 'git rm -rf --cached --ignore-unmatch DIRECTORY_NAME/' --prune-empty --tag-name-filter cat -- --all
git for-each-ref --format="%(refname)" refs/original/ | xargs -n 1 git update-ref -d

# Ensure all old refs are fully removed
rm -Rf .git/logs .git/refs/original

# Perform a garbage collection to remove commits with no refs
git gc --prune=all --aggressive

# Force push all branches to overwrite their history
# (use with caution!)
git push origin --all --force
git push origin --tags --force

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment