How to Fix Merge Conflict in Git: Simple Steps
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.
<<<<<<< HEAD console.log('Hello from main branch'); ======= console.log('Hello from feature branch'); >>>>>>> feature-branch
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.
console.log('Hello from main branch and feature branch');
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>.