Resolve Merge Conflicts
Sometimes when merging, Git cannot automatically combine changes because the same part of a file was modified differently in both branches. This is called a merge conflict. Don’t worry – Git helps you resolve it.
What Causes a Merge Conflict?
A merge conflict occurs when two branches have changes that overlap. For example, both branches modify the same line in a file, or one branch deletes a file while another modifies it. Git doesn’t know which version to keep, so it asks you to decide.
How Git Shows Conflicts
When you run
git merge and a conflict happens, Git marks the conflicted files. You’ll see a message like:Auto-merging file.txt
CONFLICT (content): Merge conflict in file.txt
Automatic merge failed; fix conflicts and then commit the result.If you open the conflicted file, you’ll see markers:
<<<<<<< HEAD
This is the version from current branch
=======
This is the version from the branch being merged
>>>>>>> feature-branch<<<<<<< HEAD marks the start of your current branch’s version.======= separates the two versions.>>>>>>> branch-name marks the end of the other branch’s version.Resolving a Conflict
To resolve:
- Edit the file to keep the lines you want (remove the markers and the unwanted lines).
- Save the file.
- Add the resolved file to staging:
git add filename. - Commit the merge:
git commit(Git will open a default merge commit message).
Using a Merge Tool
You can use a graphical merge tool to make conflict resolution easier. Set one up with:
git config --global merge.tool "meld"Then run git mergetool to launch it.Aborting a Merge
If you want to cancel the merge and go back, use:
git merge --abortThis restores your branch to the state before the merge attempt.Two Minute Drill
- Merge conflicts happen when changes overlap.
- Git marks conflicts with
<<<<<<<,=======,>>>>>>>. - Manually edit files to keep the correct changes, then
git addandgit commit. - Use
git mergetoolfor a GUI helper. - Cancel with
git merge --abort.
Need more clarification?
Drop us an email at career@quipoinfotech.com
