Remove a File from the Last Commit

GitGitBeginner
Practice Now

This tutorial is from open-source community. Access the source code

Introduction

Git is a powerful version control system that allows developers to track changes in their codebase. One of the common tasks in Git is to remove a file from the last commit. This can be useful when you accidentally added a file to the last commit that you didn't intend to include.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL git(("`Git`")) -.-> git/BasicOperationsGroup(["`Basic Operations`"]) git/BasicOperationsGroup -.-> git/commit("`Create Commit`") subgraph Lab Skills git/commit -.-> lab-12750{{"`Remove a File from the Last Commit`"}} end

Remove a File from the Last Commit

You have added a file to the last commit that you didn't intend to include. You want to remove the file from the last commit without changing its message.

For this lab, let's use the repository from https://github.com/labex-labs/git-playground. Suppose you have a Git repository named git-playground with a file named file2.txt that you accidentally added to the last commit. Here are the steps to remove the file from the last commit:

  1. Clone the repository, navigate to the directory and configure the identity:
git clone https://github.com/labex-labs/git-playground
cd git-playground
git config --global user.name "your-username"
git config --global user.email "your-email"
  1. Use git rm --cached <file> to remove the specified <file> from the index:
git rm --cached file2.txt
  1. Use git commit --amend to update the contents of the last commit, without changing its message:
git commit --amend --allow-empty

If the commit is an empty commit after deleting the file, use --allow-empty, otherwise you can leave it out.

After running these commands, the file file2.txt will be removed from the last commit without changing its message.

This is what happens when you remove file2.txt from Git version control:

On branch master

Changes to be committed:
(use "git restore --staged <file>..." to unstage)
deleted: file2.txt

Untracked files:
(use "git add <file>..." to include in what will be committed)
file2.txt

Summary

Removing a file from the last commit can be a useful skill to have when working with Git. By using the git rm --cached <file> and git commit --amend commands, you can easily remove a file from the last commit without changing its message.

Other Git Tutorials you may like