13. Cancel staged changes (before committing)

Goals

  • Learn how to undo changes that have been staged.

01 Edit file and stage changes

Make changes to the hello.html file in the form of an unwanted comment

File: hello.html

<html>
  <head>
    <!-- This is an unwanted but staged comment -->
  </head>
  <body>
    <h1>Hello, World!</h1>
  </body>
</html>

Stage the modified file.

Run

git add hello.html

02 Check the status

Check the status of unwanted changes .

Run

git status

Result

$ git status
On branch main
Changes to be committed:
  (use "git restore --staged <file>..." to unstage)
	modified:   hello.html

Status shows that the change has been staged and is ready to commit.

03 Reset the staging area

The reset command resets the staging area to HEAD. This clears the staging area from the changes that we have just staged.

Run

git reset HEAD hello.html

Result

$ git reset HEAD hello.html
Unstaged changes after reset:
M	hello.html

The reset command (default) does not change the working directory. Therefore, the working directory still contains unwanted comments. We can use the checkout command from the previous tutorial to remove unwanted changes from working directory.

04 Switch to commit version

Run

git checkout hello.html
git status

Result

$ git checkout hello.html
Updated 1 path from the index
$ git status
On branch main
nothing to commit, working tree clean

Our working directory is clean again.