Sometimes after performing a branch merging operation, developers realize they forgot or merged the wrong branch and want to undo this operation. For this purpose, execute the “$ git reset –hard <commit-ref>” command.
This study will explain the procedure to undo a git merge operation.
How Do You Undo a git merge?
To undo the git merge operation, first, navigate to the desired directory. Then, create and add files to the staging area. Commit changes to update the repository. Next, create and switch to a new branch immediately. After that, merge the two branches. Check the log history and run the “$ git reset –hard <commit-ref>” command to undo the merging procedure.
Let’s check out the above-discussed procedure practically!
Step 1: Move to Repository
First, navigate to the required Git local repository using the “cd” command:
Step 2: Create File
Run the “touch” command to create a new file:
Step 3: Track File
Now, track a newly created file by executing the “git add” command:
Step 4: Commit Changes
Next, commit changes along with a commit message using the “-m” option to update the repository:
Step 5: Create and Switch Branch
After that, execute the “git checkout” command with the branch name to create and switch to it immediately:
Step 6: Merge Branch
Now, merge the current branch with another branch by specifying its name in the git merge command:
In our case, we will merge alpha with the master branch:
Step 7: Check Log History
Check the branch log history by executing the “git log .” command:
Select and copy the commit reference which needs to undo:
Step 8: Undo git merge
Execute the “git reset” command with the “–hard” option to revert the merging process:
Note that we have also added the copied commit reference in the given command:
Step 9: Check Log History
To ensure the undo merging operation, run the “git log .” command:
We have illustrated the method to undo a git merge operation.
Conclusion
To undo the git merge operation, firstly, move to the desired directory. Then, create and add files to the staging area. Commit changes to update the repository. Next, create and switch to a new branch immediately. After that, merge the two branches. Check the log history and run the “$ git reset –hard <commit-ref>” command to undo the merging procedure. This study provided the process to undo a git merge operation.