Git Tutorial menu

Git Merging and Conflicts

Merging brings the work from one branch into another, usually a finished feature into main.

How to Merge

Go to the branch that should receive the changes, then merge the other branch into it:

Example

bash
git switch main
git merge order-form
Output
Updating 8b41d07..5c7e2d1
Fast-forward
 order.html | 1 +
 1 file changed, 1 insertion(+)
 create mode 100644 order.html

Now main has the order form. You can delete the feature branch:

Example

bash
git branch -d order-form

Two Kinds of Merge

TypeWhen it happensResult
Fast-forwardmain had no new commits since the branch startedGit just moves the main label forward
Three-way mergeBoth branches have new commitsGit creates a new merge commit joining them

A three-way merge opens an editor for the merge commit message. Save and close it to finish (in the default Vim editor, type :wq and press Enter).

Merge Conflicts

A conflict happens when both branches changed the same lines of the same file. Git cannot decide which version is right, so it asks you.

Example: on main, Ayesha changed the heading to "Ali's Bakery". On the branch new-heading, Ali changed the same line to "Fresh Bakes Karachi".

Example

bash
git merge new-heading
Output
Auto-merging index.html
CONFLICT (content): Merge conflict in index.html
Automatic merge failed; fix conflicts and then commit the result.

Reading Conflict Markers

Open index.html. Git has marked the conflict:

Example

text
<html>
<<<<<<< HEAD
<h1>Ali's Bakery</h1>
=======
<h1>Fresh Bakes Karachi</h1>
>>>>>>> new-heading
</html>
MarkerMeaning
<<<<<<< HEADStart of your current branch's version
=======Divider between the two versions
>>>>>>> new-headingEnd of the other branch's version

Resolving the Conflict

  1. Decide what the final text should be: one version, the other, or a mix.
  2. Delete the markers and keep only the final text.
  3. Stage the file and commit.

Example

text
<html>
<h1>Ali's Bakery: Fresh Bakes in Karachi</h1>
</html>

Example

bash
git add index.html
git commit -m "Merge new-heading and combine both headings"
Output
[main 7d1f3a8] Merge new-heading and combine both headings

VS Code shows conflicts with buttons: Accept Current, Accept Incoming and Accept Both. It makes resolving conflicts much easier.

Cancelling a Merge

If a merge goes wrong and you want to start again:

Example

bash
git merge --abort

Your files return to how they were before the merge.

Avoiding Conflicts

  • Merge main into your feature branch often, so you deal with small differences early
  • Keep branches short-lived: merge within days, not months
  • Talk to your team about who is editing which files
  • Make small, focused commits

Exercise

Exercise

You see <<<<<<< HEAD in a file after git merge. What should you do?

Learn Git with a teacher

Join the Full Stack Development course at Workownix, online or in Orangi Town, Karachi, and get a certificate.

See the course Ask on WhatsApp