How to Resolve Git Merge Conflicts — A Practical Guide
Merge conflicts are inevitable in collaborative development. Here's a practical guide to understanding, resolving, and preventing them.
What Causes Merge Conflicts?
A merge conflict occurs when Git can't automatically combine changes from two branches because they modify the same lines in the same file differently.
# Common scenario:
# Branch A changes line 10 to: return user.name
# Branch B changes line 10 to: return user.displayName
# Git doesn't know which one to keep → CONFLICTReading Conflict Markers
When a conflict occurs, Git inserts markers into the file:
<<<<<<< HEAD
return user.name;
=======
return user.displayName;
>>>>>>> feature-branch<<<<<<< HEAD— Your current branch's version=======— Separator between the two versions>>>>>>> feature-branch— The incoming branch's version
Resolution Strategies
1. Keep One Side
The simplest resolution — pick either yours or theirs:
git checkout --ours path/to/file # Keep your version
git checkout --theirs path/to/file # Keep their version2. Manual Merge
Often you need elements from both sides. Remove the conflict markers and write the correct combined version:
// Combined resolution:
return user.displayName || user.name;3. Use a Merge Tool
Visual merge tools make complex conflicts much easier:
git mergetool # Opens configured merge tool
git config merge.tool vimdiff # Set default toolPreventing Conflicts
- Pull frequently:
git pull --rebasekeeps your branch up to date - Small PRs: Smaller changes = fewer conflicts
- Communication: Coordinate when multiple people edit the same files
- Feature flags: Merge incomplete features without conflicting
Rebase vs. Merge Conflicts
Rebase replays your commits on top of the target branch one at a time. This means you might resolve the same conflict multiple times, but you get a cleaner history. Merge creates a single merge commit, so you resolve all conflicts at once.
# Rebase approach (cleaner history):
git rebase main
# Resolve each commit's conflicts individually
# Merge approach (single resolution):
git merge main
# Resolve all conflicts at onceQuick Reference
| Command | Purpose |
|---|---|
git status | See which files have conflicts |
git diff | View the actual differences |
git add <file> | Mark a conflict as resolved |
git merge --abort | Cancel the merge entirely |
git rebase --abort | Cancel the rebase entirely |
git log --merge | See commits causing conflicts |
Compare Your Changes
Before committing a resolution, paste both versions into DiffSnap to visually confirm what changed. Use Code Diff for syntax-highlighted comparison.
Published on DiffSnap — the free, client-side diff checker. Compare text now →