Accidentally Committed a Sensitive File in git? Here’s How to Fix It!

Aum Patel
2 min readNov 10, 2024

--

So, you’re halfway through your commits, and you realize you’ve mistakenly committed a sensitive file or folder (like an .env file) that was supposed to be ignoredand also forgot to make a .gitignore. Don’t worry—here’s a step-by-step guide to safely remove it from your commit history using Git rebase.
Steps to Remove a Sensitive File from Git History

Step 1: Start an Interactive Rebase

First, let’s open an interactive rebase session on all commits in the branch. We’ll do this with the following command:

  git rebase -i --root

This command will open a list of commits in your default text editor.

Step 2: Choose the Commit to Edit

In the editor that opens, find the commit where you accidentally added the sensitive file (or the first commit, if you’re unsure). Replace the word pick with edit next to that commit, then save and close the editor.

Step 3: Remove the Sensitive File from the Commit

Now, you’re in an editing state for that commit. Let’s remove the file from the history.

For example, if it’s an .env file, you can remove it with:

rm .env

If you have multiple sensitive files or folders, remove them here as well.

Step 4: Stage the Changes

Stage all changes (including deletions) so we can amend the commit:

git add -A

Alternatively, if you only want to remove the specific file or folder from tracking:

git rm -r --cached .env #optional

Step 5: Amend the Commit

Now that the file is removed, amend the current commit to update it:

git commit --amend --no-edit

This will update the commit without changing the commit message.

Step 6: Continue the Rebase

To apply these changes and continue through the rebase process, use:

git rebase --continue

Repeat steps 2–6 if you need to edit multiple commits.

Step 7: Update the Remote Repository

After finishing the rebase, push the changes to your remote repository. Be careful, as this step rewrites history:

git push --force origin master

And that’s it! You’ve successfully removed the sensitive file from your commit history without affecting the rest of your work. Remember, it’s always best to add sensitive files to your .gitignore before you commit, but if mistakes happen, Git gives us tools to fix them.

Follow me on linkden for more fixes like this

--

--

Aum Patel
Aum Patel

Written by Aum Patel

Devops | CKA | Penetration tester (EJPTV2) | Cloud Associate

No responses yet