16. Cancelling commits

Goals

  • To learn how to undo commits to the local repository.

01 Cancelling commits

Sometimes you realize that the new commits are wrong, and you want to cancel them. There are several ways to handle the issue, we use the safest here.

To cancel the commit we will create a new commit, cancelling the unwanted changes.

02 Edit the file and make a commit

Replace hello.html with the following file.

File: hello.html

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

Run:

git add hello.html
git commit -m "Oops, we didn't want this commit"

03 Make a commit with new changes that discard previous changes

To cancel the commit, we need to create a commit that deletes the changes saved by unwanted commit.

Run:

git revert HEAD

Go to the editor, where you can edit the default commit message or leave it as is. Save and close the file.

You will see …

Result:

$ git revert HEAD --no-edit
[master 45fa96b] Revert "Oops, we didn't want this commit"
 1 files changed, 1 insertions(+), 1 deletions(-)

Since we have cancelled the last commit, we can use HEAD as the argument for cancelling. We may cancel any random commit in history, pointing out its hash value.

Note: The --no-edit command can be ignored. It was necessary to generate the output data without opening the editor.

04 Check the log

Checking the log shows the unwanted cancellations and commits in our repository.

Run:

git hist

Result:

$ git hist
* 45fa96b 2011-03-09 | Revert "Oops, we didn't want this commit" (HEAD, master) [Marina Pushkova]
* 846b90c 2011-03-09 | Oops, we didn't want this commit [Marina Pushkova]
* fa3c141 2011-03-09 | Added HTML header (v1) [Marina Pushkova]
* 8c32287 2011-03-09 | Added standard HTML page tags (v1-beta) [Marina Pushkova]
* 43628f7 2011-03-09 | Added h1 tag [Marina Pushkova]
* 911e8c9 2011-03-09 | First Commit [Marina Pushkova]

This technique can be applied to any commit (however there may be conflicts). It is safe to use even in public branches of remote repositories.

05 Next

Next let us look at athe technique that can be used to remove the last commit from the history of the repository.

SVN?
© 2011-2014 Git How To. All rights reserved / Contact us