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 Restore the staging area

The restore command with the --staged flag clears the staging area.

Run

git restore --staged hello.html

Result

$ git restore --staged hello.html

The restore command with the --staged option does not change the actual files in the working directory. Therefore, the hello.html still contains unwanted comments. You should be careful, though, because restore without the --staged flag will also drop the changes in the working directory.

04 Restore the workign tree

Let's restore our file to the state of the last commit.

Run

git restore hello.html
git status

Result

$ git restore hello.html
$ git status
On branch main
nothing to commit, working tree clean

Our working directory is clean again.