Accidentally staged files with git add
that you don’t want to commit? No worries! Here’s how to undo git add
actions in Git.
TL;DR: Undo git add before committing
If you added files to the staging area with git add
and want to remove them before committing, use:
git restore --staged
for individual files.git reset
to unstage all changes.
Unstage Individual Files
To remove a specific file from the staging area, use:
git restore --staged <file>
Example
Suppose you’ve added example.txt
to the staging area and want to unstage
it. Run:
git restore --staged example.txt
This command keeps the changes in your working directory but removes them from the staging area.
Unstage All Files
To remove all staged files, run:
git reset
Example
If you added multiple files and need a clean slate, simply execute:
git reset
This command unstages all changes, allowing you to review and selectively re-add files.
Understanding the Commands
git restore --staged
: This command removes the specified file from the staging area while keeping changes in your working directory.git reset
: Unlikegit restore
,git reset
targets all files, clearing the entire staging area in one go.
Additional Tips for Undoing git add
Before Commit
- For Older Git Versions: If your Git version is older than 2.23, you might need to use
git reset
instead ofgit restore --staged
. - Verify the Changes: Run
git status
after using either command to ensure the files are unstaged as intended. - Use
git diff
to check differences between your working directory and the last commit, helping you review unstaged changes.
With these commands, you can quickly undo git add
before committing, whether you need to unstage
a single file or the entire staging area. Knowing these commands can help prevent unintended files from slipping into your commits, keeping your Git history clean and focused.