How to undo ‘git add’ before commit?

If you have accidentally added files to the staging area using git add and want to undo it before committing, you can use the git restore or git reset command. Here’s how to do it, with examples:


Undo git add for a Specific File

If you want to unstage a specific file:

git restore --staged <file>

Example:

git restore --staged myfile.txt

This removes myfile.txt from the staging area but keeps its changes in the working directory (your file remains modified).


Undo git add for All Files

To unstage all files that were added:

git restore --staged .

OR (using git reset):

git reset

Both commands will:

  • Remove all files from the staging area.
  • Leave your changes in the working directory.

Undo git add but Revert File Changes

If you want to not only unstage the file but also discard the changes made to it:

git restore <file>

Example:

git restore myfile.txt

This reverts the file to its last committed state (removes all changes).


Undo git add and Revert All Changes

To unstage all files and discard all changes:

git restore --source=HEAD --staged --worktree .

OR:

git reset --hard

This will:

  1. Unstage all changes.
  2. Discard any modifications in the working directory, reverting everything to the last commit.

Using Older Versions of Git

If you’re using a version of Git before git restore (introduced in Git 2.23), use git reset for similar functionality.

  • Unstage a specific file
    git reset <file>
  • Unstage all files
    git reset

Examples in Context

Scenario 1: Accidentally added a file:

git add myfile.txt
git restore --staged myfile.txt

Scenario 2: Accidentally added multiple files:

git add .
git restore --staged .

Scenario 3: Completely undo git add and discard changes:

git add myfile.txt
git restore --source=HEAD --staged --worktree myfile.txt

Scenario 4: Using git reset instead:

git add myfile.txt
git reset myfile.txt

Verify the Changes

After undoing git add, check the status to confirm:

git status

The output will indicate which files are modified but not staged for commit.


Summary of Commands

CommandDescription
git restore --staged <file>Unstages a specific file but keeps its changes.
git restore --staged .Unstages all files but keeps their changes.
git reset <file>Unstages a specific file (older Git versions).
git resetUnstages all files (older Git versions).
git restore <file>Reverts changes in the working directory for a specific file.
git restore --source=HEAD --staged .Unstages all files and discards changes.

No images available.