When merging branches, you need to tell Git how to resolve conflicting changes in different branches.
A conflict occurs when Git cannot automatically reconcile different changes made to the same part of a file.
A merge conflict happens when Git can't automatically combine branches because both branches changed the same part of a file in different ways. When this happens, Git pauses the merge and marks the conflicting sections in the affected files so you can resolve them yourself. Once you've resolved the conflicts, you can tell Git to continue the merge.
Scenario In the nouns repo (revision graph shown below), both main and fix1 modify the same location in the same file. main inserts black where fix1 inserts green.
gitGraph BT:
%%{init: { 'theme': 'default', 'gitGraph': {'mainBranchName': 'main'}} }%%
commit id: "Add colours.txt"
branch fix1
checkout fix1
commit id: "[fix1] Add green, red, white"
checkout main
commit id: "[HEAD → main] Add black, red, white"
blue
black
red
white
main branch]
blue
green
red
white
fix1 branch]
Target Merge the two branches and reconcile their conflicting changes.
Preparation
1 Try to merge the fix1 branch into the main branch. Git will pause the merge and report a merge conflict. If you open the conflicted file colours.txt, you will see something like this:
blue
<<<<<<< HEAD
black
=======
green
>>>>>>> fix1
red
white
2 Observe how the conflicted part is marked between a line starting with <<<<<<< and a line starting with >>>>>>>, separated by another line starting with =======.
The yellow highlight below shows the conflicting part from main. The HEAD label on line 2 means this conflicting change comes from the currently active branch, main:
blue
<<<<<<< HEAD
black
=======
green
>>>>>>> fix1
red
Similarly, this is the conflicting part that comes from the fix1 branch:
blue
<<<<<<< HEAD
black
=======
green
>>>>>>> fix1
red
3 Resolve the conflict by editing the file. Assume you want the merged version to keep both lines. Remove the conflict-marker lines and keep black and green:
blue
black
green
red
white
General steps for resolving a conflict:
- Remove conflict markers (e.g.,
<<<<<<< HEAD) - Edit the remaining text as needed (e.g., keep, edit, or delete one or both lines; you can also insert new text).
If there are multiple conflicts (in multiple files or different locations within the same file), resolve them the same way.
4 Stage the changes.
5 Complete the merge by doing one of the following:
- Option 1: Commit the staged changes (as you normally would).
- Option 2: Ask Git to resume the merge using the command
git merge --continue.
done!