Sometimes, you might accidentally stage files that shouldn't be committed yet. This guide will explore various methods to undo a Git add, using the git reset
and git rm
commands.
What does git add
do?
The git add
command is used to add changes in the working directory to the staging area, preparing them for the next commit. When you use git add
, you're telling Git to include updates to a particular file(s) in the next commit. However, if files are added to the staging area mistakenly, it's essential to know how to reverse this operation.
How to undo a git add
using git reset
Single file
If you need to unstage a single file, use the git reset
command:
git reset <file>
For example, to unstage a file named example.txt
, you would run:
git reset example.txt
This command moves the specified file out of the staging area (but retains the changes in your working directory).
Multiple files
To unstage multiple files, you can list them all as arguments to the command:
git reset file1.txt file2.txt
All files
If you want to undo git add .
, which stages all changes, you can reset all staged files back to the working directory without losing any changes:
git reset
This will unstage all files you've added.
Using git rm --cached to unstage files
Another method to undo git add is using the git rm --cached
command. This is particularly useful when you want to completely remove files from the staging area but keep them in your working directory, especially useful for files that were newly added to the repository and staged for the first time.
Single file
To unstage a single newly added file:
git rm --cached <file>
For instance, to unstage a newly added example.txt
:
git rm --cached example.txt
Multiple files
To unstage multiple newly added files:
git rm --cached file1.txt file2.txt
All files
For all newly added files, you can use:
git rm --cached -r .
This command recursively removes all files from the staging area while keeping them in your directory.
Practical example
Let's say you've accidentally staged several files and a directory with the git add .
command. Here’s how you can unstage them:
Check what is currently staged:
Terminalgit statusThis command will show you all the files currently staged for commit.
Unstage all changes:
Terminalgit resetThis will remove all files from staging.
Verify changes have been unstaged:
Terminalgit statusYou should see that the files are no longer staged.
For further reading see the official Git documentation.