Reverting Unstaged Changes with Git
Posted by Paolo on 5.25.23 in Git
Sometimes when I check out a branch, for example to review a Pull Request (PR) and then make a change to some of the files, I find that when I want to check out a different branch I get a Git error like the one below:
error: Your local changes to the following files would be overwritten by checkout: file-that-you-changed.html Please commit your changes or stash them before you switch branches. Aborting
In the past I have used
git stash to save the changes before trying to checkout a different branch and this also works, however, that would be more appropriate if I was actually intending to bring those changes back at some point.
I did a Google search for “git remove changes” and I found the following stack overflow question. Funnily enough, the accepted answer uses the same method I was using with
git stash, however, the answer with the most votes uses
git restore. It’s very similar to the
git add command, although it has the opposite effect. In fact if you run
git status the usage of both is explained.
In summary if you want to discard unstaged changes you can run:
git restore .
to restore all files. Or:
git restore ./a-specific-file.html
to restore a specific file.