Discarding local changes
Now that we've seen what our dear cat did, let's restore the file hello.html
to its last committed state. We can do that using the git restore command.
Run the following command in the terminal (including the period character at the end of the command):
git restore .
The .
character in git restore .
is a shorthand for the current directory. When executed that way, the command will restore all files in the current directory to their last committed state. But we can also specify a single file to restore, for example git restore hello.html
, or even a whole directory, like git restore some/path
. Using .
is just a convenient way to restore everything at once.
The git restore
command is a powerful tool, but it can also be dangerous when used carelessly. It will discard all local changes, so be careful when using it. If you're not sure what you're doing, it's better to use git status
to see what's changed, and git diff
to see the differences before deciding to discard anything.
Roll back the unintended changes with the git restore
command.
After that, run the git status
command to check whether the working tree is back to a clean state:
Run git status
to check the status of the working directory.
If everything went well, you should see the following output:
On branch main
nothing to commit, working tree clean
This is reassuring, isn't it? No matter what changes have been made, as long as they're not committed, you can always discard them and revert to the last known good state.
Old-timers among us might remember the git checkout command, which was used to discard local changes. It's still around, but it's been deprecated in favor of git restore
. The new command is more intuitive and less error-prone, so it's a good idea to get used to it.
Hi! I'm Alex, creator of GitByBit.
This page is a part of the interactive course about Git version control.
It's a one-of-a-kind course that is integrated into the VS Code code editor. Learning directly in VS Code lets you operate Git exactly as you would in real life, doing real jobs, writing real code.
In addition, the course has access to your actual terminal, so it can point out mistakes, suggest workarounds, etc.
The course is FREE, there are no Ads or other bullshit. There are optional premium add-ons you can purchase, mainly to support my work (regrettably, I have to eat every day), but that's totally up to you.