Git Tip of the day -- Remove accidentally added files
Published:
Ris Adams
View profile
Sometimes you accidentally add a file to your repository that you don’t want. It happens to all of us. Usually, it’s not that big of a deal, but it can be a problem when you commit something dangerous, such as API keys, passwords, or other sensitive information.
You might think that you can just remove the file from your repository, but that’s not always the right thing to do. You also need to eradicate the file from the git history.
This is fairly easy, but can take a while depending on how the size of your repository. (in this case we are going to assume that the file is named .secret
. This process will also work for folders, but it will take a bit longer.)
First add the file you want to remove your .gitignore
file, and commit it.
echo '.secret' >> .gitignore
git commit -a -m 'update .gitignore'
Second filter your repo to remove the unwanted files. Once complete we will force-push the changes to the remote server
git filter-branch --index-filter "git rm -rf --cached --ignore-unmatch .secret" HEAD
git push --force
As a side note, if the file you are removing contains credentials, you should consider changing any secret details that may have been exposed to the public–even if your repository is private!. With the advent of services such as Github CoPilot, even private repository details can be accessed by clever users.