Git

Deleting a Commit from a Branch in Git

Deleting a Commit from a Branch in Git

The Problem

How can you delete a commit from your branch history in Git?

The Solution

You can delete one or more recent commits from the current branch in a local repository using the git reset command. If the commit has already been pushed to a remote repository, you’ll need to force-push the changes to update the remote history.

Steps to Delete a Commit

  1. Identify the Commit to Delete:
    First, identify the commit you want to delete by using: git log
  2. Use git reset to Delete the Commit:
    • To delete the most recent commit:
    git reset --hard HEAD~1 This command moves the HEAD back by one commit and removes the most recent commit from the branch.
    • To delete a specific commit:
      Find the commit hash using git log, then reset to the commit before it:
    git reset --hard <commit-hash>^
    • To delete multiple recent commits:
      Adjust the HEAD~<number> as needed. For example, to delete the last three commits:
    git reset --hard HEAD~3
  3. Force Push to the Remote Repository:
    If the deleted commit(s) have already been pushed to a remote repository, force-push the changes to update the remote history:
    sh git push origin my-branch --force

Example Commands

  • Delete the most recent commit locally:
  git reset --hard HEAD~1
  • Delete a specific commit locally:
  git reset --hard <commit-hash>^
  • Delete the last three commits locally:
  git reset --hard HEAD~3
  • Force push to update the remote repository:
  git push origin my-branch --force

Notes

  • git reset --hard: This command is destructive as it will discard all changes and commits after the specified commit. Make sure to backup or commit any important changes before using it.
  • Force pushing: Force pushing (--force) can overwrite the history on the remote repository. Use this with caution, especially if others are working on the same branch, as it can rewrite the commit history and cause conflicts.

By following these steps, you can delete specific commits from your branch history in Git and update the remote repository accordingly.

Suggested Articles

Leave a Reply

Your email address will not be published. Required fields are marked *