How to Delete Last Commit Git: A Step-by-Step Guide

Mistakes with Git commits are inevitable, but fixing them doesn’t have to be complicated. Whether you need to undo recent changes or completely remove a commit, knowing the right Git commands can save you time and headaches. In this guide, you’ll learn the most effective ways to delete the last commit in Git, both locally and on remote repositories.

1. Remove Last Commit Locally

If you realize immediately that you need to undo last commit from your git, there are two common methods you can use:

a. Undo with Revert (Keep Commit History)

Using the git revert command creates a new commit that undoes the changes introduced by the last commit without altering the commit history. This is particularly useful when you want to remove last commit from git in a safe, reversible way.

git reset HEAD

This command tells Git to apply an inverse change to the current state, effectively nullifying your most recent commit.

b. Erase with Reset (Completely Remove Commit)

If you prefer to completely delete the last commit and its changes, you can use the git reset command. This method rewinds your branch to the commit before the last one:

git reset HEAD~1

Note: This approach completely removes the last commit from your local history. Use this command with caution, as it cannot be undone easily.

2. Git Remove Last Commit from Remote Repository

After making changes locally, if you have already pushed the commit to a remote repository, you’ll need to force update the remote branch.

Following is how to delete last commit in git from the remote:

Force Push to Overwrite Remote History

Use the following command to force push your updated history to the remote branch:

git push origin [branch] --force

Replace [branch] with the name of your branch. This command tells Git to overwrite the remote repository with your new commit history.

Remove Only from Remote (Keep Local Commit Intact)

If you wish to keep your local commit but remove it only from the remote repository, run:

git push origin +HEAD^:branch_name

This command is useful when you need to remove last commit from git remotely without losing your local work.

Conclusion

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.

Sharing Is Caring:
Subscribe
Notify of
0 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments