Sub topic 7
Resolving a Conflict Step by Step
This chapter assumes you can commit, create and switch branches, and edit files in a text editor. It also assumes you know what a conflict marker looks like. You will resolve one conflict from start to finish.
Set up the conflict
Both branches change the same line after their common commit. Run this to create the situation:
git init -b main demo && cd demo
printf 'timeout = 10\n' > config.txt
git add config.txt && git commit -m "Add config"
git switch -c feature
printf 'timeout = 60\n' > config.txt
git commit -am "Raise timeout to 60"
git switch main
printf 'timeout = 30\n' > config.txt
git commit -am "Raise timeout to 30"
git merge featureGit cannot decide between 30 and 60, so git merge stops with a conflict in config.txt. The merge is now in progress, and it stays that way until you finish or abort it.
The resolution workflow
1. Find the conflicted files
Run git status. Files listed under "Unmerged paths" need your attention. Files Git merged cleanly are already staged.
2. Read the markers
Open config.txt. Git has written both versions into it:
<<<<<<< HEAD
timeout = 30
=======
timeout = 60
>>>>>>> featureThe part between <<<<<<< and ======= is your current branch (HEAD, here main). The part between ======= and >>>>>>> comes from the branch you are merging (feature).
3. Edit to the final content
Decide what the file should contain. You can keep one side, keep the other, or combine them. Delete all three marker lines (<<<<<<<, =======, >>>>>>>) along with any text you do not want. Suppose you decide on 45 seconds. The file becomes:
timeout = 454. Mark it resolved and commit
# edit config.txt to the final content, removing all marker lines
git add config.txt
git commitStaging the file tells Git the conflict is resolved. git commit then creates the merge commit. Git opens your editor with a prepared message that you can accept as it is.
Common errors
- Committing marker lines.
git adddoes not check the file's content. If<<<<<<<remains in the file, Git will commit it. Search the file for markers before you stage it. - Resolving a file but forgetting to stage it.
git commitwill refuse and report unmerged paths. - Resolving the text but breaking the program. Two changes can merge cleanly or by hand and still be incompatible. Build and test before you commit.
Check your understanding
Exercise
After editing a conflicted file, you run git commit and Git refuses, saying there are unmerged paths. What step did you skip, and what does it do?
Show answer
You skipped git add on the edited file. Staging the file tells Git the conflict in it is resolved. After you stage every conflicted file, git commit completes the merge commit.
Exercise
In the markers above, which branch does the section between <<<<<<< HEAD and ======= belong to when you ran git merge feature while on main?
Show answer
It belongs to main, the current branch. The section after ======= is the version from feature.