How to Discard Unstaged Changes in Git

While working on a project you figure out that you made mistakes and need to undo everything. Here, you will get all answers related to the discarding of the unstaged changes in the working copy. All the changes that have been made but have not sent to the stage with git add command are considered unstaged changes.

There are three options in Git that help to undo your local changes

To view the changes that have been made in your working directory, you should run git status:

git status

Undoing changes with git stash

To discard all local changes, but also to save them for later use, you can run the git stash command:

git stash

For more information, refer to How to Stash Git Changes.

Undoing changes with git checkout

To discard local changes to a file permanently, you can run:

git checkout -- <file>

Undoing changes with git reset

To discard all local changes to all the files permanently, you can do:

git reset --hard

Staged and Unstaged Changes

The staging area (index) is a container where Git gathers all changes which will be part of the next commit.

Editing a versioned file on the local machine, will be recognized by Git as a modified file and be called as unstaged. Staging the file will place the file into the staging area. The changes within the staging area are part of the next commit. The next commit will transfer all items from the staging area into your repository. The staging area allows collecting all changes to get a clean commit.

Stashing Work

The git stash command shelves changes made to your working copy so you can do another work, get back, and re-apply them. It takes both staged and unstaged changes, saves them for further use, and then returns them from your working copy. You can delete the stash with git stash drop. To remove all the stashes, you should use git stash clear.

Cleaning Files

The git clean is an undo command that completes other commands like git reset and git checkout. Unlike the other commands, this command operates on files already added to the Git staging area and runs on untracked files. Untracked files are those created within the working directory but are not yet added to the staging area.

Git Checkout vs Git Checkout --

The git checkout command switches branches or restores working tree files. It operates on files, commits, and branches and allows switching between multiple features in just a single repository. The command works with the git branch command. It updates the files in the working directory to match the version stored in that branch, instructing Git to record all the new commits.

The -- with git checkout is a way to instruct Git what follows checkout to treat as a file, not a branch. It is used when, for example, you have a file and a branch with the same name.

Do you find this helpful?

Related articles