Skip to content

Instantly share code, notes, and snippets.

@mqnoy
Created February 13, 2026 14:59
Show Gist options
  • Select an option

  • Save mqnoy/9291be34bffc66bc36ed5d2880b81a7f to your computer and use it in GitHub Desktop.

Select an option

Save mqnoy/9291be34bffc66bc36ed5d2880b81a7f to your computer and use it in GitHub Desktop.

Emergency Guide: Removing Sensitive Files from Git History

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.

1. Immediate Local Fix (The "Oops" Moment)

If the commit is the most recent one, you can "amend" it or "reset" it.

Option A: Remove the file but keep other changes

# 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> --force

2. Deep Purge (Making it Unrecoverable)

Even 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:

Force Reflog Expiry

git reflog expire --expire=now --all

Aggressive Garbage Collection

This permanently deletes the "orphaned" data blobs from the .git database.

git gc --prune=now --aggressive

3. Verification

To 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.

4. Security Checklist ⚠️

  1. Rotate Credentials: Even if you delete the file within seconds, assume it was scraped. Change the passwords/API keys immediately.
  2. 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.
  3. 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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment