How do you resolve a merge conflict in Git?
- Technology:
- Git
Quick answer
Open the conflicted files, decide what the final code should be between the conflict markers, remove the markers, run the tests, then stage the files and continue the merge or rebase.
Detailed explanation
A conflict happens when two branches change the same lines, or one deletes a file the other edited. Git pauses the merge and marks each conflicted region with <<<<<<<, ======= and >>>>>>>. git status lists the files that need attention.
Resolving is not choosing a side. Read both changes, understand why each was made, and write the code that keeps the intent of both. Editors and git mergetool show the two versions side by side, but the decision is yours.
After editing, build and run the tests, because a conflict-free file can still be logically broken. Then git add the resolved files and run git merge --continue or git rebase --continue. If it goes wrong, git merge --abort returns you to the state before the merge.
Example
<<<<<<< HEAD
const timeout = 5000;
=======
const timeout = Number(process.env.TIMEOUT_MS);
>>>>>>> feature/config
# resolved: keep the env variable, fall back to the old default
const timeout = Number(process.env.TIMEOUT_MS ?? 5000);Real-world example
Two developers update the same configuration file: one adds a new environment variable, the other changes a default timeout. The right resolution keeps both changes, which neither "accept ours" nor "accept theirs" would do.
Key points
- git status shows conflicted files
- Combine the intent of both changes, then remove the markers
- Run tests before continuing
- git merge --abort or git rebase --abort to start over
Common mistakes
- Clicking "accept incoming" or "accept current" for the whole file without reading the other change.
- Committing files that still contain conflict markers.
- Skipping the tests after resolving, so a semantic conflict reaches main.