If you accidentally commit sensitive files (like credentials or secret keys) and push them to a remote repository, follow these steps to remove them and ensure they are unrecoverable.
If the commit is the most recent one, you can "amend" it or "reset" it.
# 1. Add the file to .gitignore so it doesn't happen again
echo "SENSITIVE_FILE_NAME" >> .gitignore
# 2. Record the removal from git tracking (without deleting from disk yet)
git rm --cached SENSITIVE_FILE_NAME
# 3. Amend the previous commit to remove the file from that commit
git add .gitignore
git commit --amend --no-edit
# 4. Force push to overwrite the remote history
git push origin <branch-name> --forceEven after a force push, the file remains in Git's internal "reflog" and "objects" for about 30-90 days. To delete it immediately and make it impossible to recover with git reflog:
git reflog expire --expire=now --allThis permanently deletes the "orphaned" data blobs from the .git database.
git gc --prune=now --aggressiveTo check if the commit still exists, try to look up its ID:
git cat-file -t <COMMIT_ID>If you see fatal: Not a valid object name, the commit has been successfully deleted from your computer.
- Rotate Credentials: Even if you delete the file within seconds, assume it was scraped. Change the passwords/API keys immediately.
- Pull Requests: If the commit was in a Pull Request, the PR history might still show it. You may need to delete the branch on GitHub/GitLab and create a new one.
- Collaborators: Anyone who pulled the "bad" commit before you fixed it still has it. Tell your team to delete their local branch and re-pull.