Course contentsShow
← Git & GitHub
Lesson 38 of 963. Branching and TeamworkFree lesson

Resolving Conflicts During Branch Merges

You will identify and manually fix code conflicts that occur when two branches modify the same lines of a file simultaneously.

In this lesson, you will learn how to manually resolve code conflicts that happen when Git cannot automatically merge two branches.

The Anatomy of a Conflict

Sometimes, you might modify the same line of a file in two different branches. When you try to merge those branches, Git pauses and asks for your help because it doesn't know which version you prefer. This is called a merge conflict.

When a conflict occurs, Git marks the file with special "conflict markers." If you open the file in your editor, you will see something like this:

<<<<<<< HEAD
print("Hello from the main branch!")
=======
print("Hello from the feature branch!")
>>>>>>> feature-branch
  • <<<<<<< HEAD: Everything below this line until the separator belongs to the branch you are currently on.
  • =======: This is the divider between your two changes.
  • >>>>>>> feature-branch: Everything above this line back to the divider belongs to the branch you are trying to merge in.

How to Resolve It

Resolving a conflict is a manual process of cleaning up the file:

  1. Open the conflicted file in your text editor.
  2. Delete the markers: Remove the <<<<<<<, =======, and >>>>>>> lines.
  3. Edit the code: Keep the lines you want, or rewrite them to include both features if necessary. Your goal is to make the file look exactly how you want the final code to be.
  4. Save the file.
  5. Finalize: Run git add <file> to mark the file as resolved, then run git commit to finalize the merge.

Git will automatically detect that you’ve finished the resolution once you complete the commit. Since you are manually selecting the code that stays, you act as the final judge, ensuring that your project remains functional even when two developers change the same lines.

Key Takeaway: Merge conflicts aren't errors, but invitations to manually reconcile competing changes by removing conflict markers and staging the final, corrected version of your code.