Git : Merge Conflict

This demo uses a simple scenario involving two branches to show what happens when changes clash.

Step 1: Set Up Your Repository

  1. Create a new directory for your project and navigate into it:
   mkdir git-demo
   cd git-demo
  1. Initialize a new Git repository:
   git init

Step 2: Create a Base File

  1. Create a new file called example.txt and open it in a text editor.
  2. Add some content to the file, such as:
   Hello, world!
   This is a Git merge conflict demonstration.
  1. Add and commit the file to the repository:
   git add example.txt
   git commit -m "Initial commit"

Step 3: Create Branches

  1. Create and switch to a new branch called feature:
   git branch feature
   git checkout feature
  1. Make changes to example.txt in the feature branch. For example, change the second line to:
   This is a feature branch version.
  1. Commit the changes:
   git add example.txt
   git commit -m "Update from feature branch"

Step 4: Create a Conflict

  1. Switch back to the main branch:
   git checkout main
  1. Make different changes to the same line in example.txt. Change the second line to:
   This is the main branch version.
  1. Commit these changes:
   git add example.txt
   git commit -m "Update from main branch"

Step 5: Attempt to Merge and Resolve Conflict

  1. Try to merge the feature branch into the main branch:
    This will result in a merge conflict because both branches modified the same line of the same file.
   git merge feature
  1. Open example.txt and you will see something like this:
   Hello, world!
   <<<<<<< HEAD
   This is the main branch version.
   This is a feature branch version.
   >>>>>>> feature
  1. Resolve the conflict by editing the file to incorporate both changes or choose one over the other. For example:
   Hello, world!
   This is the merged version from both branches.
  1. Add the resolved file to the staging area and complete the merge:
   git add example.txt
   git commit -m "Resolved merge conflict"

This step-by-step guide provides a hands-on way to demonstrate and resolve merge conflicts, helping you understand how Git handles simultaneous changes to the same part of a file by different branches.

Hello, I’m Anuj. I make and teach software.

My website is free of advertisements, affiliate links, tracking or analytics, sponsored posts, and paywalls.
Follow me on LinkedIn, X (twitter) to get timely updates when I post new articles.
My students are the reason this website exists, crafted with the affection and dedication they’ve shown. ❤️

Feedback Display