Git provides a command git rm
It works the same as the rm
command but will remove the file from your git repository.
So you have made a boo boo. Worse still you have committed a secret file with an API key. What do?
Alright so we can't do that for whatever reason. Now what?
1link$# First thing you do is change the visibility of the repo. So, if it's a public repo, make it private. This way, you're sure no one else sees the file while you're working on deleting it.
2link$
3link$cd my-repo
4link$
5link$# Then run the following command. You have to include the path to the file and not just the file name. replacing config/secretFile.json with the path to the file you want to be removed. In my case, secretFile.json is inside of a folder named config.
6link$
7link$git filter-branch --force --index-filter \
8link$ "git rm --cached --ignore-unmatch config/secretFile.json" \
9link$ --prune-empty --tg-name-filter cat -- --all
10link$
11link$# Note: The command above deletes the file from your local repository too, so ensure you have copied the content to a notepad or whatever you use before running the command.
12link$
13link$# Then create and add your file to .gitignore so you don't accidentally push it to GitHub again. You can do that with
14link$
15link$echo "name-of-your-file" >> .gitignore
16link$git add .gitignore
17link$git commit -m 'add file to .gitignore'
18link$
19link$# Once you are satisfied with your changes, you can then push them to GitHub
20link$
21link$git push origin --force --all
22link$
23link$#And that's it! Your repo history is clean without any trace of your sensitive file.
Home Backstory Why Git? Setting Up GitHub GitHub CLI Your GitHub Profile GitHub Pages Creating A New Repo Cloning A Repository Your First Commit Ignoring Files In Git Stashing Your Changes Branching With Git Merging Git Branches Rebasing Vs Merging Git Workflows Fork And Pull Flow Your First Pull Request Automated Security Alerts Seeing The Differences Removing/Deleting Files Reverting Your Commits Configuring your Git Commit Templates Creating Shortcuts Dotfile Management Sponsoring Open Source Handy Commands Thank You