However, when working in a git repository, you need to add the files and directories in the next commit explicitly.
Before committing your changes, you will have to add them to the staging area.
In some instances, you may add a file or a directory to the staging area before it’s ready or includes a file that should not be there.
This tutorial aims to help you learn how you can undo a git add operation. Before committing, you can use the undo operation to remove files from your staging area.
Install or Update Git
You must ensure first that you have the latest version of git installed.
On Windows, you can download the installer in the resource below:
On Debian based distributions, install git with the command:
$ sudo apt-get install git -y
To update git to the latest version, execute the command below on your Windows terminal.
On Linux, run the git install command to update to the latest version.
Undo Git Add – Restore
As of git version 2.23 and above, you can use the git restore command to undo a git add operation.
Before undoing an add operation, it is good to view the changes that need to be commited.
You can use the command:
We can see the files and directories in the staging area from the above output.
To remove the eof.py file from the staging area:
The –staged flag tells git to remove the file from the staging index while still preserving the changes made to the file.
You can verify this by running the git status command:
Notice the eof.py is no longer available in the staging area. Now you make changes to the file and commit it once you are ready.
You can also specify a wildcard character to undo all the files matching a specific extension.
For example, to undo the add operation for all the .py files:
The command will successfully remove all the files ending in .py extension from the staging area.
If you want to remove a file from the staging area and discard all the changes made to the file, you can use the git restore command without the –staged flag.
The restore command without the –staged flag discards all the changes made to the files.
Undo Git Commit – Reset
You can also undo a git add operation using the git reset command. The command syntax is as shown:
To remove all the files from the staging area:
Unlike the git restore without staging, the git reset command will preserve the changes made to the files.
This tutorial taught you how to undo a git add operation using the git restore and git reset commands.
We also covered when to and not to use the git restore command with the —staged flag.