How to remove a committed file from Git history forever
Using Git version control is second nature to most developers, and it provides many useful features and functions. However, there may come a time when a file is committed to the repository that should have been excluded, such as an .env
file containing environment variables. In this article, we'll explore the steps necessary to remove such a committed file from your Git history forever.
Step 1. Add the ignored file to the .gitignore file
The first thing you need to do is add your file to the .gitignore
file in your repository. In this case, you'll just add .env
to the .gitignore
.
# .gitignore
.env
This will prevent future commits from accidentally uploading the file. However, it does not remove existing commits from the history.
Step 2: Remove the .env file from your Git history
To permanently remove the .env
file from your Git history, we can use the filter-branch command. This command essentially rewrites the history of the branch, and can be used with an index filter to selectively remove files.
git filter-branch --index-filter "git rm -rf --cached --ignore-unmatch .env" HEAD
The above command tells Git to rewrite the history, removing any file that matches with an .env
extension. The --cached
argument tells Git to remove the paths only from the index, not from disk, and --ignore-unmatch
causes it not to fail on non-existent files (they may have already been deleted in some commits).
Step 3: Push the filtered changes
The final step is to commit the changes to the repository:
git push --force
Note that force-pushing should generally be avoided because it replaces the remote commits with your local commits. But in this case it is necessary because we have rewritten the history.
Summary
If we accidentally commit a file that should have been ignored, Git gives us powerful tools to rewrite the history and remove that file forever. Note that these operations should be used with care, as they can irreversibly change your commit history.
Happy safe pushing!