How to Discard Unstaged Changes in Git

When using Git, it is common to make changes that you want to remove entirely before the staging phase. For example, after working on a few files, you realize that you want to revert the changes made to one specific file. To discard the changes before staging and committing, use the $ git checkout command.

To unstage one file :

$ git checkout <path-to-file>

Remember to replace <path-to-file> with the actual file name.

To unstage all files:

$ git checkout -- .

Git Checkout

The git checkout command switches between branches or restores working tree files. There are a number of different options for this command that won’t be covered here, but you can take a look at all of them in the Git documentation.

Checkout a specific commit

To checkout a specific commit, run the command:

git checkout specific-commit-id

We can get the specific commit id’s by running:

git log

Checkout an Existing Branch

To checkout an existing branch, run the command:

git checkout BRANCH-NAME

Generally, Git won’t let you checkout another branch unless your working directory is clean, because you would lose any working directory changes that aren’t committed. You have three options to handle your changes: 1) trash them, 2) commit them, or 3) stash them.

Checkout Previous Branch

To checkout previous branch, run the command:

git checkout -

git checkout - is a shorthand for git checkout @{-1} .

Checkout a New Branch

To create and checkout a new branch with a single command, you can use:

git checkout -b NEW-BRANCH-NAME

This will automatically switch you to the new branch.

Checkout a New Branch or Reset a Branch to a Start Point

The following command is similar to checking out a new branch, but uses the -B (note the captital B) flag and an optional START-POINT parameter:

git checkout -B BRANCH-NAME START-POINT

If the BRANCH-NAME branch doesn’t exist, Git will create it and start it at START-POINT . If the BRANCH-NAME branch already exists, then Git resets the branch to START-POINT . This is equivalent to running git branch with -f .

Force a Checkout

You can pass the -f or --force option with the git checkout command to force Git to switch branches, even if you have unstaged changes (in other words, the index of the working tree differs from HEAD ). Basically, it can be used to throw away local changes.

When you run the following command, Git will ignore unmerged entries:

git checkout -f BRANCH-NAME

# Alternative
git checkout --force BRANCH-NAME

Undo Changes in your Working Directory

You can use the git checkout command to undo changes you’ve made to a file in your working directory. This will revert the file back to the version in HEAD :

git checkout -- FILE-NAME
3 Likes