Thursday, 31 October 2024

How to undo last commit in Git

 

If you need to undo the last merge in Git, you can take a couple of approaches depending on your situation. Below are the common methods:

1. Undo the Last Merge Commit

If you want to undo the last merge commit and return to the state before the merge:

      git reset --hard HEAD~1

  • This command will reset your current branch to the commit before the last one, removing the merge commit. Be careful: This will discard any changes made in the merge.

2. Undo a Merge But Keep Changes

If you want to undo the merge but keep the changes in your working directory, use:

      git reset --soft HEAD~1

  • This command moves the HEAD pointer back one commit but keeps all changes in the staging area. You can then review or modify them before committing again.

3. Revert a Merge Commit

If the merge has already been pushed to a remote repository and you want to keep the history but effectively "undo" the merge, you can use:

      git revert -m 1 <merge_commit_hash>

  • Replace <merge_commit_hash> with the hash of the merge commit you want to revert. The -m 1 option indicates that you want to keep the first parent of the merge.

Example Workflow

  1. Find the Merge Commit Hash: You can see the history with:

      git log --oneline

Look for the commit that represents the merge.

  1. Revert the Merge Commit: Use the revert command:

      git revert -m 1 <merge_commit_hash>

Important Notes

  • Always make sure to check your current branch and commit history before performing destructive actions like reset --hard.
  • If you're working in a shared repository, communicate with your team when undoing merges to avoid confusion.
  • If you've already pushed the merge commit to a remote repository, consider using git revert instead of reset to maintain a clear history.

 

No comments:

Post a Comment