Git & Command Line Tutorial · Branching and Collaboration · Lesson 14 of 20
Merging and Resolving Conflicts
Bring branches together with git merge, understand fast-forward vs merge commits, and resolve conflicts when two branches changed the same lines.
Merging
git merge feature brings the commits of feature into the current branch:
- Fast-forward: if the current branch hasn't moved since
featurebranched off, Git simply moves the pointer forward. - Merge commit: if both branches have new commits, Git creates a commit with two parents.
Conflicts
If both branches changed the same lines, Git can't decide and stops with a conflict. The file shows both versions between markers:
<<<<<<< HEAD
the current branch's version
=======
the other branch's version
>>>>>>> feature
To resolve: edit the file to the final content (remove the markers), git add it, then git commit. git merge --abort cancels the merge instead. Editors like VS Code show buttons for "accept current / incoming / both".
git init -b main --quiet team && cd team
printf "Title: Welcome\nColor: blue\n" > settings.txt
git add . && git commit -m "Add settings" --quiet
git switch -c feature/title --quiet
sed -i 's/Welcome/Welcome to our shop/' settings.txt && git commit -am "Better title" --quiet
git switch main --quiet
git merge feature/title | head -1 # main hadn't moved: a fast-forward
git switch -c feature/green --quiet
sed -i 's/blue/green/' settings.txt && git commit -am "Make it green" --quiet
git switch main --quiet
sed -i 's/blue/red/' settings.txt && git commit -am "Make it red" --quiet
git merge feature/green > /dev/null || echo "CONFLICT! settings.txt now contains:"
cat settings.txt
printf "Title: Welcome to our shop\nColor: green\n" > settings.txt # decide on the final content
git add settings.txt && git commit --no-edit --quiet
git log --oneline --graph | head -5
Output
Updating 078dffd..23104a0 CONFLICT! settings.txt now contains: Title: Welcome to our shop <<<<<<< HEAD Color: red ======= Color: green >>>>>>> feature/green * e9d8833 Merge branch 'feature/green' |\ | * eb0b228 Make it green * | 9835ae6 Make it red |/
Run this on your computer — see “Get Started” for setup.
Test yourself
After fixing the conflict markers in a file, what do you run?
git pushgit add the file, then git commitgit merge --abortgit reset
Show answer
Answer: git add the file, then git commit