0
0
GitConceptBeginner · 3 min read

What Is Merge Conflict in Git: Simple Explanation and Example

A merge conflict in Git happens when two branches have changes in the same part of a file and Git cannot automatically decide which change to keep. It requires a developer to manually choose or combine the changes before completing the merge.
⚙️

How It Works

Imagine two friends writing a story on the same page but each writes different sentences in the same spot. When they try to combine their pages, they find conflicting sentences and must decide which to keep or how to mix them. This is like a merge conflict in Git.

In Git, when you merge branches, it tries to combine changes automatically. But if both branches changed the same lines differently, Git stops and asks you to fix the conflict. You then edit the file to choose or merge the changes, and tell Git when you are done.

💻

Example

This example shows a simple merge conflict between two branches editing the same line in a file.

bash
git init example-repo
cd example-repo
echo "Hello World" > file.txt
git add file.txt
git commit -m "Add greeting"
git branch feature

git checkout feature
echo "Hello from feature branch" > file.txt
git commit -am "Change greeting in feature"

git checkout main
echo "Hello from main branch" > file.txt
git commit -am "Change greeting in main"

git merge feature
Output
Auto-merging file.txt CONFLICT (content): Merge conflict in file.txt Automatic merge failed; fix conflicts and then commit the result.
🎯

When to Use

You encounter merge conflicts when working with others or on multiple branches that change the same files. Resolving conflicts is essential to combine everyone's work correctly.

Use merges regularly to keep branches updated and resolve conflicts early. This helps avoid big conflicts later and keeps your project history clean.

Key Points

  • A merge conflict happens when Git cannot automatically combine changes.
  • It requires manual editing to resolve differences.
  • Conflicts usually occur when multiple people edit the same lines.
  • Resolving conflicts keeps your project consistent and up to date.

Key Takeaways

A merge conflict occurs when two branches change the same part of a file differently.
Git stops the merge and asks you to manually fix the conflict.
Resolving conflicts ensures all changes are combined correctly.
Regular merging helps catch conflicts early and keeps work in sync.