Merge conflicts in git

Philip Thomas K.

23 November 20

Back

If you work with git and you are faced with the task of merging branches, there may be this uneasy feeling just before you execute the merge that it won’t work perfectly. This happens when git does not know what to do when the lines it has to consolidate and merge together conflict each other.

So, if you run the merge command and it tells you that there has been a merge conflict, it means that you need to step in to fix the conflict.

What do you need to know, git-wise?

Right after git says there is a merge conflict, you need to realise that you are technically suspended in the middle of the merge commit. Nothing has been commited yet, and every file that has conflicts will be unstaged.

In the files with the merge conflicts, there will be portions denoted as such:

<<<<<<< HEAD
[content from current master branch that HEAD is pointing to]
=======
[content that git is trying to merge automatically]
>>>>>>> new_branch_to_merge_later

What do you need to do?

All you have to do when you reach this part is to edit it into the end state. This is the only part where subject matter knowledge is required. Make sure you delete the angle brackets and equal signs put in by git.

Once this is completed to satisfaction, save the file, then add the files to the staging area with git add [files]. After which, you need only run the following command:

$ git commit

This should merge cleanly, with the standard git merge commit message template in place.

What do I do if I mess up?

I can’t know what sort of errors you run into, git-wise. However, some tips for git troubleshooting may help. To view git history in a sensible way that gives more insight as to the state of git, use this instead of git log or git reflog:

$ git log --oneline --decorate --all --graph

And if you want to jump back to a pre-merge state, simply run the following:

$ git reset --hard [commit HASH]

Where [commit HASH] is the hash of the commit which you wish to jump back to.

General rules to follow pre-merge

Make sure you are on the correct branch when you run the command above. Also make sure that you are on the correct branch when you plan to execute a merge.

Best Regards,
Philip

Back