How to Remove a File from a Git Commit: A Step-by-Step Guide

It’s important to know how to remove a file from a Git commit. You’ll do a better job managing your project’s version control. You’ll also be able to correct any mistakes without losing progress or compromising the integrity of your repo.

This post covers different approaches to removing files from Git commits. It’ll also give you some ideas for how to maintain a clean and accurate version history.

How to undo the last commit and retain changes in Git?

If you need to remove a file from your last commit and want to keep the changes for additional editing, the git reset command offers a direct solution. This command is perfect for quickly retracting a recent commit while still saving all changes outside the staging area.

git reset HEAD~1

Run this command to roll back the most recent commit and keep your changes. You can then selectively add and commit files, excluding the one you intend to remove.

How to remove the file from the repository but keep it locally?

When your goal is to remove a file from the repository but still retain it on your local machine, use the git rm --cached command. This approach is ideal for files that were mistakenly added to the repository but are necessary for your local environment.

git rm --cached <file-name>

Make sure to commit this change to effectively remove the file from the repository's tracking:

git commit -m "Remove <file-name> from repository"

How to amend the previous commit to remove the file?

To remove a file from a commit you just made, amending the commit can be an effective strategy. First, untrack the file with git rm --cached if you haven't already, and then amend the commit:

git commit --amend

This action opens the commit editor, allowing you to adjust the commit message as needed, effectively recreating the commit without the unwanted file.

How to remove the file from an older commit in Git?

Removing a file from an older commit requires a bit more finesse and involves rewriting history with git rebase. This method should be approached with caution, especially when dealing with commits that have been pushed or are part of a shared history.

git rebase -i <commit-hash>^

In the interactive mode, choose the commit you wish to edit by marking it with edit. Git will stop at that commit, giving you the chance to remove the file:

git rm <file-name> git commit --amend

To continue with the rebase process, execute:

git rebase --continue

Adopting this approach to remove a file from a commit should be done thoughtfully, particularly in shared repositories, to prevent disrupting your team's workflow.

For removing sensitive data from your history, consider using git filter-branch or the BFG Repo-Cleaner for a more targeted approach that goes beyond simply removing a file from a commit.

Invite only

We're building the next generation of data visualization.