How to Delete Local Commits in Git

John Wachira Feb 02, 2024
How to Delete Local Commits in Git

This article will discuss the steps to undo local commits. We will see how to delete a single commit to multiple commits in Git.

Delete Local Commits in Git

We will discuss how to delete the latest commits in your local repository to kick things up.

We usually use the git reset command to delete the latest changes to our repository. If you want to delete the latest commit, use the command below.

git reset --hard HEAD~1

The argument HEAD~1 will delete one commit.

We can use an N-th argument, as shown below.

git reset --hard HEAD~N

If you want to delete the last five commits in your repository, replace N with your value.

We can delete a specific commit with the command below.

git reset --hard <sha1-commit-hash>

Commit history

Use your equivalent of the above in the command.

If you want to undo changes made by a commit located in-between your commit history, use the git revert command. This command will undo the changes made by the selected commit.

git revert <sha1-commit-hash>

However, git revert will not delete the commit. We use the git rebase in the interactive form.

git rebase -i <sha1-commit-hash>

You will see an editor with a list of the surrounding commits after running the command above. You can type drop at the beginning to delete the commit you want.

If you want to push the changes to your remote repository, run the command below.

git push --force-with-lease origin HEAD

The command above will not affect the changes made by other developers in the remote repository. It is a safer option for the git push origin HEAD --force command which overwrites all changes made by other developers in a remote repository.

If you want to revert your local changes to the current state of your remote repository, run the command below.

git reset --hard origin/<branch_name>

You can find a deleted commit with the git reflog command.

Author: John Wachira
John Wachira avatar John Wachira avatar

John is a Git and PowerShell geek. He uses his expertise in the version control system to help businesses manage their source code. According to him, Shell scripting is the number one choice for automating the management of systems.

LinkedIn

Related Article - Git Reset

Related Article - Git Revert