0
0
GitDebug / FixBeginner · 3 min read

How to Handle Merge Conflict in Git: Simple Steps

A merge conflict happens when Git cannot automatically combine changes from different branches. To handle it, open the conflicting files, decide which changes to keep, edit the files to resolve conflicts, then use git add and git commit to complete the merge.
🔍

Why This Happens

A merge conflict occurs when two branches have changes in the same part of a file and Git cannot decide which change to keep. This usually happens when multiple people edit the same lines or when you edit a file locally and someone else changed it remotely.

diff
<<<<<<< HEAD
console.log('Hello from branch A');
=======
console.log('Hello from branch B');
>>>>>>> feature-branch
Output
Auto-merging example.js CONFLICT (content): Merge conflict in example.js Automatic merge failed; fix conflicts and then commit the result.
🔧

The Fix

To fix a merge conflict, open the file with conflict markers like <<<<<<< HEAD and >>>>>>> feature-branch. Choose which code to keep or combine both, then remove the conflict markers. After editing, save the file, run git add <file> to mark it resolved, and finish with git commit.

javascript
console.log('Hello from branch A and branch B');
Output
Merge made by the 'recursive' strategy. example.js | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-)
🛡️

Prevention

To avoid merge conflicts, communicate with your team to avoid editing the same lines simultaneously. Pull changes often with git pull before starting work. Use small, focused commits and branches. Tools like git rebase can help keep history clean and reduce conflicts.

⚠️

Related Errors

Other common Git errors include rebase conflicts, which are similar to merge conflicts but happen during rebasing. Also, detached HEAD state can confuse beginners when switching branches. Both require careful file edits and commands to fix.

Key Takeaways

Merge conflicts happen when Git can't auto-merge changes in the same file area.
Resolve conflicts by editing files, removing markers, then adding and committing.
Pull changes often and communicate to reduce conflicts.
Use small branches and commits for easier merges.
Rebase conflicts are similar and need careful resolution.