Loading...

Git Tutorial

Cancelling commits in git

Lets learn how to undo commits to the local repository.

Step1: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, and we use the safest here.

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


Step2: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"

Step3: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.



Step4:Check the log

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

RUN:

git hist

RESULT:

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

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.

Next

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