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 redo the previous git commit?

Redo the previous git commit

In this post, I provide the necessary commands to revise or redo the previous git commit. There are cases when you make an incomplete commit, you miss some files, or you would like to change the content of some files in the last commit. With the following command, you can reset your last commit:

git reset --soft HEAD~1
  • --soft Does not touch the index file or the working tree at all. This leaves all your changed files “Changes to be committed”, as git status would put it. [source: man git-branch]

After that, you can further change the content of the file or stage new files. When you are ready, you can stage the changes and craft a new commit.

Update the changes in the remote repository

If you pushed your commit to the remote repository before the redo, you must force-push the revised commit. This can be done as follows:

git push --force origin <branch_name>

Demonstration

The video below demonstrates the described commands above: