How to undo the last git commit in the repository?

In this post, I present a simple git command to revert/undo the last git commit in the local and remote repository.

Undo the last git commit in the local copy

There are cases when new commits are added to the git repository by mistake and you need to roll back the changes. This can be done by using the revert command:

git reset --hard HEAD~2
  • HEAD~2 reset the current branch back by two commits. If you change this to HEAD~1 then it will reset the last commit only. The number can be change in accordance to your need, number of commit to be reset,
  • --hard reset your files to the ones found in HEAD~2.

Undo the last git commit in the remote repository

To push the content to the remote repository type the following to the command line:

git push --force origin <branch_name>

Demonstration

The video below demonstrates the described commands above:

How to remove/undo/unstage files added through git add?

There might be cases when you added files (temporary, libraries, executes, etc.) by executing for example git add --all. Before or during the commit you notice that they shall not be included in the git repository. In this post I demonstrates how to remove/undo/unstage files added/staged accidentally.

Unstage a single file

Let’s say test.cpp~ was added by accident and you would like to undo the add. This can be done as follows:

git reset test.cpp~

Unstage multiple files

If you need to remove multiple files, wildcards can be used, for example:

git reset *.cpp~

Unstage all the added/staged files

If you need to undo all the added files you can use git reset without additional inputs.

git reset

Demonstration

The video below demonstrates the described git commands above: