0
0
GitDebug / FixBeginner · 4 min read

How to Fix Merge Conflict in Git: Simple Steps

A merge conflict in git happens when changes in two branches clash. To fix it, open the conflicting files, decide which changes to keep, edit the files to remove conflict markers, then use git add and git commit to complete the merge.
🔍

Why This Happens

A merge conflict occurs when Git cannot automatically combine changes from two branches because the same part of a file was changed differently in each branch. This usually happens when two people edit the same lines of code or text.

diff
<<<<<<< HEAD
console.log('Hello from main branch');
=======
console.log('Hello from feature branch');
>>>>>>> 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 the conflict, open the file with conflict markers like <<<<<<<, =======, and >>>>>>>. Choose which code to keep or combine both. Remove the conflict markers, save the file, then run git add <file> and git commit to finish the merge.

javascript
console.log('Hello from main branch and feature branch');
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 about changes, pull updates often, and work on smaller, focused branches. Use git pull --rebase to keep your branch updated before merging. Also, use code reviews and automated tests to catch conflicts early.

⚠️

Related Errors

Other common Git errors include rebase conflicts, which happen during git rebase and are fixed similarly by resolving conflicts and continuing the rebase with git rebase --continue. Another is detached HEAD, which means you are not on a branch and can be fixed by checking out a branch with git checkout <branch>.

Key Takeaways

Merge conflicts happen when the same file lines are changed differently in branches.
Fix conflicts by editing files to remove conflict markers and choosing the correct code.
Use git add and git commit to complete the merge after resolving conflicts.
Pull changes often and communicate with your team to prevent conflicts.
Rebase conflicts are fixed similarly by resolving and continuing the rebase.