Sep 19, 2024

Permanently remove a file from git history

git
Permanently remove a file from git history

As human beings, we all make mistakes. As developers, we might accidentally push a file containing sensitive information to a git repository. And even tho if we revert the commit, it would still be present on the git history of the project.

In such cases, where we want to permanently remove a file from a git history, we need to perform a couple of weird steps.

#. 1. Your file is probably not ignored by git, so add it to .gitignore file.

#. 2. Permanently remove a file from Git history:

(assuming .env is the file you want to remove)

bash
git filter-branch --index-filter "git rm -rf --cached --ignore-unmatch .env" HEAD

This can be a time-consuming process as it revisits all of the git commits in history and removes the file from there.

#. 3. Force push changes

Since we modified a bunch of commits, we will have to do a force push to modify the git history of the project.

bash
# git push -u origin main --force git push --force

#. 4. Remove from only project

If you only want to remove file from project, not from git history. (make sure you've it in .gitignore file):

bash
git rm -r --cached .env

#. GitGuardian

To not repeat this, you can use a Github app called GitGuardian.
Simply install it in your account or specific repo, it will alert you if you push any secrets to github, and it will send you an email too.