DEV Community

Devtonight
Devtonight

Posted on • Updated on • Originally published at devtonight.com

How To Undo Staged (Indexed) Changes In Git

In this question, we are going to discard and undo staged (index) changes in a Git repository. If you need to clean unstaged files, you can refer to this question.

First, stage all the files required to discard with the git add command.

git add .
Enter fullscreen mode Exit fullscreen mode

If you only need to discard some specific files, stage them like this.

git add file1 file2 file3
Enter fullscreen mode Exit fullscreen mode

Discard Staged Changes With Git Reset

We can use git reset with --hard to discard staged files. After running the git reset command, all the changes of the staged files including the newly created and existing files will be discarded.

git reset --hard
Enter fullscreen mode Exit fullscreen mode

Discard Staged Changes With Git Stash

The main intention of Git Stash is to move current changes into a separate temporary area so you can continue with something else and the stashed changes can be applied later. But we can use the Git Stash to discard staged changes as well. After running the git stash command, all the staged changes will be disappeared and move to the stash list.

git stash
Enter fullscreen mode Exit fullscreen mode

Now you will be able to see the stash list by running this command.

git stash list
Enter fullscreen mode Exit fullscreen mode

If you need, you can remove the lastly created stash.

git stash drop stash@{0}
Enter fullscreen mode Exit fullscreen mode

Or otherwise, clean the entire stash list.

git stash clear
Enter fullscreen mode Exit fullscreen mode

Unstage First, Then Discard Approach

It is obvious, git reset and git stash commands do the job quickly in one go. However, you can use the following commands to unstage the staged files first and then discard them using the commands we explained in the How To Discard Undo Changes In Git Working Directory question.

Unstage all the staged files using the git restore command.

git restore --staged .
Enter fullscreen mode Exit fullscreen mode

Unstage some specific files.

git restore --staged file1 file2 file3
Enter fullscreen mode Exit fullscreen mode

Unstage all the staged files using the git reset command.

git reset
Enter fullscreen mode Exit fullscreen mode

Unstage some specific files.

git reset file1 file2 file3
Enter fullscreen mode Exit fullscreen mode

Feel free to visit devtonight.com for more related content.

Top comments (0)