How do I undo 'git add' before commit?
How Do I Undo 'git add' Before Commit?
If you've added files to the staging area using git add
but want to undo this action before committing, you can use the git reset
command. This will unstage the files, moving them back to the working directory without making any changes to the files themselves.
Steps to Unstage Files
Unstage All Files
To unstage all files that have been added to the staging area:
git reset
Unstage a Specific File
To unstage a specific file that has been added to the staging area:
git reset <file>
Example:
git reset myfile.txt
Example Workflow
-
Stage the Files:
git add myfile.txt anotherfile.txt
-
Check the Status:
git status
Output:
Changes to be committed: (use "git restore --staged <file>..." to unstage) new file: myfile.txt new file: anotherfile.txt
-
Unstage All Files:
git reset
-
Unstage a Specific File:
git reset myfile.txt
-
Verify the Status Again:
git status
Output:
Changes not staged for commit: (use "git add <file>..." to update what will be committed) (use "git restore <file>..." to discard changes in working directory) modified: myfile.txt modified: anotherfile.txt
Using git restore
(Git 2.23+)
In Git 2.23 and later, you can also use the git restore
command to unstage files.
Unstage All Files
git restore --staged .
Unstage a Specific File
git restore --staged <file>
Example:
git restore --staged myfile.txt
Summary
To undo git add
before committing, you can use the git reset
command to unstage the files. If you're using Git 2.23 or later, you can also use the git restore --staged
command. Here are the commands for quick reference:
-
Unstage all files:
git reset
or
git restore --staged .
-
Unstage a specific file:
git reset <file>
or
git restore --staged <file>
By following these steps, you can easily undo the git add
command before committing, ensuring that only the desired changes are staged. For more in-depth knowledge and practical examples of Git and other coding practices, consider exploring Grokking the Coding Interview on DesignGurus.io, which provides comprehensive courses on essential coding and interview techniques.
GET YOUR FREE
Coding Questions Catalog