12. Discarding local changes (before staging)
Goals
- Learn how to discard the working directory changes.
01 Checking out the main
branch
Make sure you are on the latest commit in the main
branch before you continue.
Run
git switch main
02 Change hello.html
Sometimes you have modified a file in your local working directory and you wish to just revert to what has already been committed. The checkout
command will handle that.
Make changes to the hello.html
file in the form of an unwanted comment.
File: hello.html
<html>
<head>
</head>
<body>
<h1>Hello, World!</h1>
<!-- This is a bad comment. We want to revert it. -->
</body>
</html>
03 Check the status
First of all, check the working directory’s status.
Run
git status
Result
$ git status
On branch main
Changes not staged for commit:
(use "git add <file>..." to update what will be committed)
(use "git restore <file>..." to discard changes in working directory)
modified: hello.html
no changes added to commit (use "git add" and/or "git commit -a")
We see that the hello.html
file has been modified, but not staged yet.
04 Undoing the changes in the working directory
Use the checkout
command in order to check out the repository's version of the hello.html
file.
Run
git checkout hello.html
git status
cat hello.html
Result
$ git checkout hello.html
Updated 1 path from the index
$ git status
On branch main
nothing to commit, working tree clean
$ cat hello.html
<html>
<head>
</head>
<body>
<h1>Hello, World!</h1>
</body>
</html>
The status
command shows there were no unstaged changes in the working directory. And the "bad comment" is no longer contained in the file.