Merge conflicts occur in Git when changes from two branches affect the same part of a file and Git cannot automatically merge them. This guide explains how to identify, resolve, and finalize merge conflicts effectively.
A merge conflict can happen when:
- Multiple contributors make changes to the same line in a file.
- One branch modifies a file while another branch deletes it.
- Different branches modify overlapping parts of a file.
During a merge, Git will notify you of conflicts:
Auto-merging file.txt
CONFLICT (content): Merge conflict in file.txt
Automatic merge failed; fix conflicts and then commit the result.
To see which files have conflicts:
git status
Conflicted files will appear under the section "Unmerged paths".
Conflicting files will contain conflict markers like these:
<<<<<<< HEAD
Changes from the current branch.
=======
Changes from the branch being merged.
>>>>>>> feature_branch
HEAD
: Represents changes from the branch you are currently on.- Below
=======
: Represents changes from the branch you are merging.
Manually edit the file to integrate or choose the changes you want to keep. Remove the conflict markers once resolved.
Example Before Resolving:
<<<<<<< HEAD
This is line 1 from the main branch.
=======
This is line 1 from the feature branch.
>>>>>>> feature_branch
Example After Resolving:
This is the integrated line 1 from both branches.
After editing, stage the resolved file:
git add file.txt
Finalize the merge by committing:
git commit -m "Resolve merge conflicts"
Invoke Git's merge tool for easier conflict resolution:
git mergetool
You can use external GUI-based merge tools like:
- VS Code (built-in Git support).
- Sourcetree.
- Meld.
- KDiff3.
To configure a tool globally:
git config --global merge.tool tool_name
If resolving conflicts becomes too complex or you want to abandon the merge:
git merge --abort
This resets the branch to its state before the merge started.
- Communicate with Your Team: Discuss conflicts, especially when collaborating.
- Resolve Small Changes Often: Regularly merge branches to minimize conflicts.
- Use Descriptive Commit Messages: Clearly describe how conflicts were resolved.
Command | Description |
---|---|
git status |
List conflicting files. |
git diff |
View differences in conflicting files. |
git mergetool |
Launch the configured merge tool. |
git add file.txt |
Mark the conflict as resolved. |
git merge --abort |
Abort the merge process. |
Attempt to merge:
git merge feature_branch
Check the conflicted files:
git status
Open the conflicting file in a text editor, resolve the conflicts, and save.
git add resolved_file.txt
git commit -m "Resolve merge conflict in resolved_file.txt"
Merge conflicts are a natural part of collaborative workflows. By understanding how to identify and resolve conflicts, you can ensure smooth integration of changes and maintain project stability.
Next Steps: Remote Repositories