Merge conflicts are a normal part of working with Git, especially when collaborating on shared code.
A merge conflict occurs when Git cannot automatically combine changes between branches because the same part of a file was modified in two different ways.
Understanding how conflicts happen and how to fix them is an essential Git skill.
Why Merge Conflicts Happen
Merge conflicts usually occur when:
- Two branches modify the same line of code
- One branch deletes a file that another branch edits
- Two developers edit the same file simultaneously
- Automatic merge is not possible due to overlapping changes
Git stops the merge and asks for human intervention.
Creating a Merge Conflict (Example)
Imagine two branches: main and feature/update-title
On main, the file says:
title = "Homepage"On feature/update-title, the file says:
title = "New Homepage Title"When merging feature/update-title into main:
git checkout main
git merge feature/update-titleGit will detect conflicting edits on the same line and stop the merge.
What a Merge Conflict Looks Like
Git adds special markers to show the conflicting sections inside the file:
<<<<<<< HEAD
title = "Homepage"
======
title = "New Homepage Title"
>>>>>>> feature/update-titleMeaning of markers:
- HEAD block = your current branch
- After ====== = incoming changes
- After >>>>>>> = which branch the change came from
How to Resolve a Merge Conflict
Steps to fix the conflict:
- Open the conflicted file
- Decide which version to keep
- Remove all conflict markers
- Save the resolved file
- Stage the file:
git add filename- Complete the merge:
git commitGit now records a merge commit that includes your resolved changes.
Resolution Options
Depending on the situation, you may choose to:
- Keep your version
- Keep the incoming version
- Combine both changes
- Rewrite the section completely
Example combining both:
title = "Homepage - New Title"Using Git Merge Tools
Git supports external merge tools for easier conflict resolution.
Set a mergetool globally:
git config --global merge.tool vimdiffRun the merge tool:
git mergetoolCommon tools:
- vimdiff
- kdiff3
- meld
- Beyond Compare
Viewing Conflict Status
List files with conflicts:
git statusGit displays:
both modified: filenameAborting a Merge
If you want to cancel the merge and restore the previous state:
git merge --abortUseful when the conflict is too complicated or the merge attempt was a mistake.
Summary
In this chapter, you learned:
- What merge conflicts are and why they happen
- How Git marks conflicted sections
- How to manually resolve conflicts
- How to stage and commit resolved files
- How to use Git mergetool
- How to abort a merge if necessary
Merge conflicts are completely normal and nothing to fear.
With practice, they become easy to understand and resolve efficiently.
Next, we will explore Git workflow models such as feature branching, Git Flow, and trunk-based development.