Undo a git add

 

How to undo a staged Git file

The proper way to undo the git add command is to use git restore.

  • git restore –staged file.py

I have seen other tutorials recommend git reset or git rm, but these commands are not designed for the specific task of removing a staged file in Git and should be avoided:

  • git reset file-to-unstage.js
  • git rm –cached JavaClassToUnstage.java

Unstage and undo a git add example

To undo a git add on a file named HelloWorld.java, the command would be:

git restore --staged HelloWorld.java

Here’s a quick, real-world example of how to unstage a Git file in Git. In this example we:

  • Perform a git clone command on a sample GitHub repository
  • Add a new file using the touch command
  • Stage the new file in Git’s index
  • Undo the git add command with git restore

In  this example you will also see the git status command. This command helps view the current state of the file.

$ git clone https://github.com/cameronmcnz/ufe.git
Clone the repo

$ cd ufe
Move to project folder

$ touch new-file.html
Create a new file

$ git status
Files not tracked: new-file.html

$ git add new-file.html
$ git status
Changes to be committed: new file: new-file.html

$ git restore --staged new-file.html
Git add undone successfully

$ git status
Untracked files: new-ile.html

Example of the rm to unstage Git commands

The git restore command is relatively new, only being introduced in 2019.

Before the introduction of the git restore command, the git reset command was used by developers to undo a git add.

git reset this-file.txt

You can still undo a git add with this command, but it’s not the preferred choice.

Avoid the git rm command

An extreme measure for undoing a git add is the git rm command

git rm --cached new-file.txt

Avoid git rm.

You will not only undo the git add, but if used incorrectly, the file may be removed both from Git and from your project.

Need to undo a git add and unstage a file in git?

Use the git restore command. It’s the best option.

App Architecture
Software Quality
Cloud Computing
Security
SearchAWS
Close