To resolve merge conflicts in Git, follow these steps:
1. Identify Conflicted Files
- When a conflict occurs during a merge or rebase, Git will list the conflicted files.
git status
- Look for files under “Unmerged paths”.
2. Open the Conflicted Files
- Use a text editor or IDE to open files marked with conflict markers:
plaintext
<<<<<<< HEAD Your current branch's changes
======= Incoming branch's changes
>>>>>>> branch-name
<<<<<<< HEAD
to=======
: Your changes (current branch).=======
to>>>>>>> branch-name
: Incoming changes (from the merged branch).
3. Resolve the Conflicts
- Choose one version:
- Keep your changes: Delete the incoming code and markers.
- Keep incoming changes: Delete your code and markers.
- Combine both: Manually edit the code to merge changes (e.g., keep both features).
- Remove all conflict markers (
<<<<<<<
,=======
,>>>>>>>
).
4. Stage the Resolved Files
git add <file1> <file2> # Stage resolved files
- Use
git add .
to stage all resolved files.
5. Complete the Merge/Rebase
- For a merge:
bash git commit -m "Resolved merge conflicts"
- For a rebase:
bash git rebase --continue
Optional Tools & Commands
- Use a merge tool:
git mergetool # Launches a visual tool (e.g., vimdiff, VS Code)
- Abort the merge/rebase:
git merge --abort # Cancel a merge
git rebase --abort # Cancel a rebase
- Checkout specific versions:
git checkout --ours <file> # Keep your branch's version
git checkout --theirs <file> # Keep the incoming branch's version
Example Workflow
- Merge
feature-branch
intomain
and hit a conflict:
git checkout main
git merge feature-branch
- Resolve conflicts in
app.js
using an editor. - Stage and commit:
git add app.js
git commit -m "Merge feature-branch and resolve conflicts"
Tips to Avoid Conflicts
- Pull changes frequently:
git pull origin main
. - Communicate with your team about overlapping changes.
- Use smaller, focused commits.
By following these steps, you’ll efficiently resolve merge conflicts and keep your project history clean!