Programación Para Tontos

Git

Tutorial: resolve your first Git conflict

Learn to read and resolve a Git merge conflict without panicking.

A merge conflict happens when Git doesn't know which of two changes to keep, because both touched the same line. It sounds terrifying the first time. It isn't. Let's cause one on purpose to lose the fear of it.

Step 1: set up the conflict scenario

echo "Original version" > file.txt
git add file.txt
git commit -m "Original version"

git checkout -b branch-a
echo "Change from branch A" > file.txt
git commit -am "Change on branch A"

git checkout main
echo "Change from main" > file.txt
git commit -am "Change on main"

Now you have two different versions of the same line, on two different branches. Time to merge them.

Step 2: attempt the merge

git merge branch-a

Git will show something like CONFLICT (content): Merge conflict in file.txt. It's not a fatal error, it's Git telling you "I need you to decide".

Step 3: open the file and decide

<<<<<<< HEAD
Change from main
=======
Change from branch A
>>>>>>> branch-a

Everything between <<<<<<< HEAD and ======= is your current version. Everything between ======= and >>>>>>> branch-a is the version you were trying to merge in. Edit the file by hand, keep whichever content you want, and delete those marker lines (<<<<<<<, =======, >>>>>>>).

Step 4: mark the conflict as resolved

git add file.txt
git commit -m "Resolve conflict between main and branch-a"

Running git add on the edited file tells Git "I've decided, this is the final content". The commit closes out the merge.

What did you just learn?

  • Why a merge conflict happens (two changes on the same line).
  • How to read the <<<<<<<, =======, and >>>>>>> markers.
  • That resolving a conflict is just editing the file and committing again, nothing magical or scary.