Sometimes, after committing changes to a Git repository, we may realize that we made a mistake or want to undo the commit. In this blog post, we will learn to remove the last commit from the git remote repository branch through the “git revert” command. So that we can undo the commit that we did earlier.
To use this command, we need to open a terminal or command prompt and navigate to the local repository where we want to make the change. Then, we can use the following command to revert the last commit:
1. Delete from local
We can delete the last commit locally by using the following command.
git revert HEAD
This command will create a new commit that undoes the changes made in the last commit. It is important to note that this does not delete the commit from the repository, but rather creates a new commit that reverses the changes made in the previous commit.
If you want to delete the last commit and all the changes made in it, you can use the “git reset” command instead. This command allows you to discard commits, moving the branch pointer to a previous commit and destroying the commits in the process.
To delete the last commit using the “git reset” command, you can use the following command:
git reset HEAD~1
This command will delete the last commit and all the changes made in it, moving the branch pointer to the commit before the last one. It is important to note that this operation is not reversible, so it should be used with caution.
2. Delete from remote repository
If you have already pushed the commit to a remote repository, you will need to use the “git push” command with the “–force” option to overwrite the remote repository with the new commit history. For example:
git push origin [branch] --force
The above step should remove the last commit from the git remote repository as well as local.
Replace “[branch]” with the name of the branch that you want to update. This command will force push the new commit history to the remote repository, replacing the previous commits.
If you want to keep it in the local and want to delete it from the remote repository only then use the following command,
git push origin +HEAD^:branch_name
In this post, we learn to remove the last commit message from the git remote repository branch as well as the local branch. If you want to remove the last N number of commits from your git repository then you can visit another post on how to remove the last N number of commits in git.