14. Discarding local changes (before staging)

Goals

  • To learn how to discard the working directory changes

01 Checking out the Master branch

Make sure you are on the lastest commit in the master brach before you continue.

Run:

git checkout master

02 Change hello.html

It happens that you modify a file in your local working directory and sometimes wish just to discard the committed changes. Here is when the checkout command will help you.

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 master
# Changes not staged for commit:
#   (use "git add <file>..." to update what will be committed)
#   (use "git checkout -- <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 checkout the repository’s version of the hello.html file.

Run:

git checkout hello.html
git status
cat hello.html

Result:

$ git checkout hello.html
$ git status
# On branch master
nothing to commit (working directory 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.