How to Delete a Local Commit in Git

You might occasionally need to delete a local Git commit. Maybe because of an error. Or maybe the changes were unnecessary. The good news is that Git is forgiving. In this post we’ll show you how to actively delete a local commit in Git.

How to delete the most recent commit in local repository?

To remove the most recent commit, use the reset command. This action effectively rewinds your current branch to the state before the last commit, while keeping your working directory's changes intact.

git reset --soft HEAD~1

The --soft flag ensures that your changes remain in your working directory. If you prefer to discard the changes completely, opt for the --hard flag instead.

git reset --hard HEAD~1

How to delete an older commit in Git?

Removing an older commit requires a bit more effort, involving the rebase command. Begin by identifying the hash of the commit you wish to delete through the commit history.

git log

Then, initiate an interactive rebase for the commits up to the one you're aiming to remove. For instance, if the target commit is four commits back, execute:

git rebase -i HEAD~5

In the text editor that appears, you'll see a list of commits starting from the one you specified. To delete a commit, either remove its line or change the word pick to drop beside the commit you're targeting. Completing and closing the editor will commence the rebase.

How to delete a commit from a branch in Git?

To delete a commit from a specific branch, first check to make sure you're on that branch:

git checkout branch-name

Proceed by following the earlier mentioned steps to delete the most recent or an older commit, based on what your situation demands.

Caution

Exercise caution when deleting commits, particularly if they have been pushed to a shared repository. Deleting commits alters the history and can disrupt the workflow for others on the same project. If the commit has been pushed, consider using git revert instead, which negates the changes with a new commit, avoiding the pitfalls of history rewriting.

Invite only

We're building the next generation of data visualization.