How to permanently remove a file from Git history

We all make mistakes sometimes. Pushing files that contain some secrets or sensitive information to a Git repository is fairly common. And even if we revert the commit, it would still be present in the Git history of the project. In such cases, where we want to permanently remove a file from Git history, we need to perform a couple of steps.

1. If the file involved some secrets, revoke them immediately

- Advertisement -

2. Add the file to gitignore.

Assuming it was a .env file,

echo '.env' >> .gitignore

3. Permanently remove a file from Git history:

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

If it is a different file, replace “.env” with the path of the file.

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

4. Force push

git push --force

Since we rewrote a bunch of commits, we will have to do a force push to modify the git history of the project. If there are multiple branches on the project, or a team working on the project, this might be cumbersome and we would want to search for the commits manually and rebase them instead.

Note: If we only wanted to remove the file and did not care about deleting it from the git history, we would have used the command:

git rm -r --cached .env

And that is it. Drop-in a comment below if you have any questions.

Recent Articles

Overriding nested dependencies in NPM

Whenever we install a particular package, it is common to come across a problem with a dependency's dependency. With the release of...

Automatic batching in React 18 helps avoid re-rendering

Remember the earlier versions of React that used to batch multiple state updates inside event handlers such as click or change to...

Flatten Arrays in Vanilla JavaScript with flat() and flatMap()

ES2019 introduced two methods on the array prototype that would make life so much simpler for developers. These are flat() and flatmap()...

Using GroupBy on an array of objects in JavaScript

Array grouping is a fairly common operation in any project. Until recently, we had to resort to either writing our own implementation...

Node.js introduces node: protocol imports

Node.js recently introduced a node: protocol for built-in modules. Built-in node modules can now be imported by prefixing the node: protocol prefix.

Related Stories

Leave A Reply

Please enter your comment!
Please enter your name here

Hi there! Want some more knowledge?

Think that the knowledge shared is helpful? You might want to give our mailing list a try. We'll send you 2-4 emails a month, right when new posts come out.

Hi there! Want some more knowledge?

Think that the knowledge shared is helpful? You might want to give our mailing list a try. We'll send you 2-4 emails a month, right when new posts come out.