In this tutorial, we will be discussing how to resolve merge conflicts in GitHub. Merge conflicts often arise when attempting to combine code from different branches. The goal of this tutorial is to help you understand the process of resolving such conflicts.
By the end of this tutorial, you will learn:
Prerequisites: Basic understanding of Git and GitHub.
A merge conflict happens when two branches you're trying to merge both changed the same part of the same file, Git won't be able to figure out which version to use. When such a situation occurs, Git stops right before the merge commit so that you can resolve the conflicts manually.
Best practice: Always pull
the recent changes before you start your work.
Git will tell you that a merge conflict has occurred right after you run a git merge
command.
Here's how to resolve a merge conflict:
Identify the files with conflicts: Git will list out the files that have merge conflicts.
Resolve the conflicts: Open the files and you'll see the conflicting changes.
Add the resolved files: After resolving the changes, add these files with git add
.
Commit the resolved changes: Finally, you can commit the resolved changes with git commit
.
Let's go through an example:
You run git merge feature-branch
and find a conflict in file.txt
.
Open file.txt
, and you'll see something like this:
<<<<<< HEAD
This is some content from the master branch.
======
This is some different content from the feature branch.
>>>>>> feature-branch
This is the resolved content.
file.txt
to the staging area:$ git add file.txt
$ git commit -m "Resolved merge conflict in file.txt"
The -m
flag lets you add a commit message right from the command line.
In this tutorial, we've learned about what a merge conflict is, how to detect one, and the steps to resolve it.
For further learning, you can look into more complex merge conflicts and how to prevent them.
Here's a useful resource: Resolving a merge conflict from the command line
Exercise 1: Create a new branch, make changes to the same part of the same file in both this new branch and the master branch. Try to merge these branches.
Exercise 2: Resolve the conflict you created in Exercise 1.
Exercise 3: Create two new branches, make different changes to the same part of the same file in both these branches. Merge these branches into the master branch, one after the other, resolving conflicts as they come up.
Tip: Practice is key. Try creating and resolving conflicts a few times until you're comfortable with the process.