How to discard local changes in Git

Kenny DuMez
Kenny DuMez
Graphite software engineer


Note

This guide explains this concept in vanilla Git. For Graphite documentation, see our CLI docs.


Discarding local changes in Git is especially useful when you need to revert your working directory to a clean state or synchronize it with a remote repository. This guide provides an overview of how to discard local changes in your Git environment using several commands.

Discarding changes can be necessary in several scenarios, such as:

  • Reverting edits that introduced errors or undesirable effects.
  • Preparing to pull updates from a remote repository and wanting to avoid merge conflicts.
  • Switching branches then changes that are not relevant to the new branch.

To discard all local changes in your working directory, including both staged and unstaged changes, you can use a single command:

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

This command uses the git restore command to revert both the staging area and the working directory to the state of the last commit, which is referred to by HEAD:

  • --source=HEAD specifies that you want to restore from the last commit.
  • --staged and --worktree indicate that changes in both the staging area and the working directory should be undone.
  • -- . applies the restore to all files in the current directory and subdirectories.

If you only need to discard changes in specific files rather than the entire project, run:

Terminal
git checkout <file_path>

Replace <file_path> with the path to the file you wish to revert. This command will restore the specified file to its state at the last commit.

To switch branches and discard local changes related to the current branch, you can run:

Terminal
git checkout -f <branch_name>

Here, <branch_name> is the name of the branch you want to switch to. The -f flag forces Git to discard local changes, allowing you to switch branches without needing to clean your working directory separately.

To discard local changes and immediately update your branch with the latest changes from the remote repository, run:

Terminal
git reset --hard HEAD
git pull origin <branch_name>

First, this command resets the branch to the last. Then, it pulls the latest changes from the remote repository for the specified branch.

  • Always double-check which changes are being discarded: Use git status to review changes before discarding them permanently.
  • Consider stashing changes instead of discarding: If you want to revisit the changes later, use git stash to save them instead of discarding them.
Git inspired
Graphite's CLI and VS Code extension make working with Git effortless.
Learn more

Graphite
Git stacked on GitHub

Stacked pull requests are easier to read, easier to write, and easier to manage.
Teams that stack ship better software, faster.

Or install our CLI.
Product Screenshot 1
Product Screenshot 2