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