{"id":338,"date":"2022-06-16T00:00:00","date_gmt":"2022-06-16T00:00:00","guid":{"rendered":"https:\/\/tac.debuzzify.com\/?p=338"},"modified":"2023-06-24T06:27:23","modified_gmt":"2023-06-24T06:27:23","slug":"delete-file-from-git-history","status":"publish","type":"post","link":"https:\/\/www.the-analytics.club\/delete-file-from-git-history\/","title":{"rendered":"A Step-by-Step Guide to Permanently Deleting a File from Git History"},"content":{"rendered":"\n\n\n

It happens to me all the time.<\/p>\n\n\n\n

I create repositories, and I know that I need to store my secret keys in an environment file. But I always commit my changes without adding them to the gitignore file.<\/p>\n\n\n\n

As a result, our secrets are there on the internet!<\/p>\n\n\n\n

Now, even if you add the environment file to gitignore, it won\u2019t go from the history.<\/p>\n\n\n\n

The severity could vary depending on what information you\u2019ve uploaded and how difficult it is to reset it. Yet, it’s preventable! So, we should always stop such sensitive data from entering the cloud.<\/p>\n\n\n\n

But, If you accidentally pushed something, here\u2019s how to properly remove sensitive data from git history.<\/p>\n\n\n\n

Properly remove secret files from git history.<\/b><\/h2>\n\n\n\n

Committing a secret file (such as .env) becomes part of the git history. Removing the file and recommitting it won\u2019t clear it. Adding it to the gitignore at a later point won\u2019t help either.<\/p>\n\n\n\n

Previously, people used git-filter-branch to tap into the branching model. Trust me; you don\u2019t want to get in there.<\/p>\n\n\n\n

If you disagree, here\u2019s the warning message on git-filter-branch documentation<\/a>.<\/p>\n\n\n\n

\n

git filter-branch<\/b> has a plethora of pitfalls that can produce non-obvious manglings of the intended history rewrite \u2014 Git filter branch documentation<\/p>\n<\/blockquote>\n\n\n\n

Fortunately, we have a simpler alternative. It\u2019s called BFG repo-cleaner.<\/a><\/p>\n\n\n\n

BFG is a community-maintained utility. It\u2019s written in Java. So make sure you have it ready on your computer.<\/p>\n\n\n\n

How NOT to remove a secret file from Git.<\/b><\/h2>\n\n\n\n

Let\u2019s create a sample repo for this walkthrough.<\/p>\n\n\n\n

I created a repo with only one file. It\u2019s a .env file with a secret key in it. With it, I made my initial commit. Now the `.env` file should be in the history.<\/p>\n\n\n\n