Resolve a merge conflict
Merge conflicts are a natural part of collaborative development in Git, occurring when conflicting changes are made to the same file or code section. While merge conflicts can initially seem daunting, they provide an opportunity to bring diverse ideas together and achieve code harmony. Resolving merge conflicts is an essential skill that ensures a smooth integration of changes and maintains a cohesive codebase.
In this part of our tutorial, we will guide you through the process of resolving merge conflicts in Git.
Let’s merge the branches issue2
and issue3
we created in the last step into the main branch.
First, switch to main
and merge issue2
using a fast-forward merge.
$ git checkout main
Switched to branch 'main'
$ git merge issue2
Updating b2b23c4..8f7aa27
Fast-forward
myfile.txt | 2 ++
1 files changed, 2 insertions(+), 0 deletions(-)
This is now the history:
Next, try to merge issue3
into main
.
$ git merge issue3
Auto-merging myfile.txt
CONFLICT (content): Merge conflict in myfile.txt
Automatic merge failed; fix conflicts and then commit the result.
In this case, Git has identified a conflict because the myfile.txt
file has different content on the same line on each branch and cannot automatically merge issue3
with main
.
The myfile.txt
file will now look something like this:
Anyone can learn Git with this tutorial and Backlog
add: Register a change in an index
<<<<<<< HEAD
commit: Save the status of an index
=======
pull: Obtain the content of a remote repository
>>>>>>> issue3
You will find markers added to the myfile.txt
file by Git with information regarding the conflict. We must manually fix the conflict, as shown below.
Anyone can learn Git with this tutorial and Backlog
add: Register a change in an index
commit: Save the status of an index
pull: Obtain the content of a remote repository
Once the conflict is resolved, commit the change.
$ git add myfile.txt
$ git commit -m "merge issue3 branch"
# On branch main
nothing to commit (working directory clean)
And the history will look like this:
You can see that a new merge commit has been created as a result of the conflict resolution. And the main branch is now pointing to the latest merge commit. This is a non-fast-forward merge.