← Git

Coding challenge

Challenge 003 - Trigger and resolve a merge conflict

Scenario

You are going to trigger a conflict on purpose to learn how to resolve it calmly. You will create two branches that modify the same line of a file, try to merge them, and resolve the resulting conflict.

A conflict is not an error: it is Git asking you to decide which version to keep.

How to solve it

# --- Set up the scenario ---
# On main, create a file with one line
echo "Titulo original" > titulo.txt
git add titulo.txt
git commit -m "Agrega titulo original"

# Create the feature branch and change the SAME line
git switch -c feature
echo "Titulo desde feature" > titulo.txt
git commit -am "Cambia titulo en feature"

# Go back to main and change the same line in a different way
git switch main
echo "Titulo desde main" > titulo.txt
git commit -am "Cambia titulo en main"

# --- Trigger the conflict ---
git merge feature
# CONFLICT (content): Merge conflict in titulo.txt
# Automatic merge failed; fix conflicts and then commit the result.

Why it happens

Both branches modified the same line of titulo.txt. Git can merge changes that are in different areas, but when two branches touch the same line in different ways, it cannot guess which one you want: it asks you to decide.

Full solution

View commented solution
# 1. See which file is in conflict
git status
# both modified: titulo.txt

# 2. Open titulo.txt: you will see the conflict markers
# <<<<<<< HEAD
# Titulo desde main
# =======
# Titulo desde feature
# >>>>>>> feature

# 3. Edit the file to leave the correct version and DELETE the markers.
#    For example, you decide to keep a mix:
echo "Titulo definitivo" > titulo.txt

# 4. Mark the conflict as resolved
git add titulo.txt

# 5. Close the merge with a commit (Git already provides a default message)
git commit -m "Resuelve conflicto en titulo.txt"

# Verify
git log --oneline --graph

If you get stuck: git merge --abort cancels the merge and returns you to the previous state, as if you had never tried it.

Key point: you must delete the three markers (<<<<<<<, =======, >>>>>>>) before running git add. Git does not check that you did it; it trusts that you left the file correct.