You’ve most probably used Git as a version control system for a project or two if you're a regular developer. While using Git is relatively straightforward, it's not impossible to run into some issues. One such situation that developers often find themselves in is when they need to remove files from a commit.

Read on as we showcase how you can remove a file from Git commit.

Understanding Git States

Before jumping into how you can remove a file from a commit, you need to understand the different Git workflow states for a file.

There are four possible states when working with a file in Git. The first is the untracked state—files that you create and have not yet pushed or staged exist in this state. The Git repository is not tracking these files.

Laptop screen with initial react code and logo

Once you use the git add command on a file, it becomes staged and moves to the second state. Git stage essentially readies the file to be committed. The third state involves the commit command; the git commit command moves the staged file onto the branch alongside the newly made changes.

Files that have already been committed but modified since the last commit are said to be in the modification state.

Git Remove File From Commit

To remove a file that has been committed to a branch or Git repository, you can utilize the git reset command as follows:

git reset --soft HEAD^

This will effectively bring back the committed files to the staging area.

If you want to further remove a file from the staging area, use the git reset command once more. A file that has been removed from the staging area will not be committed to the branch.

git reset HEAD <FILENAME>

You can then make the required modifications, stage your files using git add, and finally use git commit to push your changes onto the repository.

git rm -- cached filename
    

git commit --amend

Remove File From Commit

Git is an essential tool for every developer out there; knowing how to remove files from commit is a vital skill every aspiring and experienced developer needs to know.

For those who are eager to learn, Git has many more valuable features that you can explore and utilize to improve your daily workflow.