The Wayback Machine - https://web.archive.org/web/20240822105416/https://www.geeksforgeeks.org/merge-conflicts-and-how-to-handle-them/
Open In App

Merge Conflicts and How to handle Them in Git

Last Updated : 30 Jun, 2024
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Merge conflicts are a common challenge developers face when working with Git. Understanding what they are and how to resolve them effectively is important for smooth collaboration in any project.

Understanding how to handle merge conflicts is important for maintaining a smooth workflow. This article will explain what merge conflicts are, why they happen, and how to resolve them effectively.

What Are Merge Conflicts?

A merge conflict happens when Git is unable to automatically reconcile differences in code between two commits. This typically occurs during a merge operation, where changes from different branches are combined.

Why Do Merge Conflicts Occur?

Merge conflicts usually arise in the following scenarios:

  1. Simultaneous Edits: Two developers modify the same line of code in different branches.
  2. Conflicting Changes: A file is deleted in one branch and modified in another.
  3. Complex Merges: When multiple branches are being merged, with changes scattered across various files and lines.

Types of Merge Conflicts

While starting the merge: If there are changes in either the working directory or staging area, while merging, then Git will fail to start the merge. This happens because the pending changes could be overridden by the commits that are being merged. This is the error message provided by Git when this type of merge conflict happens :

error: Entry '<fileName>' not uptodate. Cannot merge. (Changes in working directory)
or,
error: Entry '<fileName>' would be overwritten by merge. Cannot merge. (Changes in staging area)

This type of conflict can be resolved either by doing git stash save “any_message_to_describe_what_is_saved” (Stashes away any changes in your staging area and working directory in a separate index) OR git checkout <file_name> (throws out your changes), and then the merge can be completed.

During the merge: This occurs because you have committed changes that are in conflict with someone else’s committed changes. Git will do its best to merge the files and will leave things for you to resolve manually in the files it lists. This is the error message provided by Git when this type of merge conflict happens :

CONFLICT (content): Merge conflict in <fileName>
Automatic merge failed; fix conflicts and then commit the result.

This type of conflict can be resolved either by manually fixing all the merge conflict for each file OR using git reset ––hard (resets repository in order to back out of merge conflict situation).

Creating a merge conflict

To show a simple example of how a merge conflict can happen, we can manually trigger a merge conflict from the following set of commands in any UNIX terminal / GIT bash :

Step 1: Create a new directory using the mkdir command, and cd into it.

Step 2: initialize it as a new Git repository using the git init command and create a new text file using the touch command.

Step 3: Open the text file and add some content in it, then add the text file to the repo and commit it.

CreatingmergeconflictPart1

Step 4: Now, its time to create a new branch to use it as the conflicting merge. Use git checkout to create and checkout the new branch.

Step 5: Now, overwrite some conflicting changes to the text file from this new branch.

Step 6: Add the changes to git and commit it from the new branch.

With this new branch: new_branch_for_merge_conflict we have created a commit that overrides the content of test_file.txt

Step 7: Again checkout the master branch, and this time append some text to the test_file.txt from the master branch.

Step 8: add these new changes to the staging area and commit them.

Step 9: Now for the last part, try merging the new branch to the master branch and you will encounter the second type of merge conflict.

So, now we have successfully triggered a merge conflict in Git.

Handling the Merge Conflict

As we have experienced from the proceeding example, Git will produce some descriptive output letting us know that a CONFLICT has occurred. We can gain further insight by running the git status command. This is what we will get after running the git status command:

On branch master
You have unmerged paths.
(fix conflicts and run "git commit")
(use "git merge --abort" to abort the merge)

Unmerged paths:
(use "git add <file>..." to mark resolution)
both modified: test_file.txt

no changes added to commit (use "git add" and/or "git commit -a")

On opening the test_file.txt we see some “conflict dividers”. This is the content of our test_file.txt :

<<<<<<< HEAD
Adding some content to mess with it later
Append this text to initial commit
=======
Changing the contents of text file from new branch
>>>>>>> new_branch_for_merge_conflict

The ======= line is the “center” of the conflict. All the content between the center and the <<<<<<< HEAD line is content that exists in the current branch master which the HEAD ref is pointing to. Alternatively, all content between the center and >>>>>>> new_branch_for_merge_conflict is content that is present in our merging branch.

To resolve our merge conflict, we can manually remove the unnecessary part from any one of the branches, and only consider the content of the branch that is important for further use, along with removing the “conflict dividers” from our file. Once the conflict has been resolved we can use the git add command to move the new changes to the staging area, and then git commit to commit the changes.


Previous Article
Next Article

Similar Reads

How does NPM handle version conflicts ?
Consider a case where we have installed a module say A. Now we want to install another module called B and B depends on A but the problem is the version of A which is required by module B is different from the version of A installed at first. So how npm will handle this situation where our application depends on two different versions of module A.
3 min read
Difference Between Git remote prune, Git prune and Git fetch --prune
Git is a version control system that helps developers manage and track changes in their codebase. Among its many commands, git remote prune, git prune, and git fetch --prune are essential for maintaining a clean and organized repository. This article will explain the differences between these commands, their syntax, uses, and provide examples to il
4 min read
Git Merge and Merge Conflict
Let us discuss what merging in git. Merging means combining changes from one branch into another branch. Now let's see how can we perform merging here we can see that we can see one log in the master branch. Merging Changes Now let's check out the logs in the dev branch and here we can see there are two logs in the dev branch. So now as we can see
2 min read
How to use @layer rule to overcome cascading styles conflicts in CSS ?
A cascade layer is declared using the @layer CSS at-rule, which can also be used to specify the hierarchy of precedence when there are multiple cascade layers. With this, web developers have more control over cascades as a result of rules that layer cascades together. Any styles that are not in a layer are collected and added to a single anonymous
3 min read
How CSS Styles Conflicts Between Selectors ?
CSS conflicts between selectors occur when two or more selectors have conflicting styles applied to the same element, leading to unexpected results. In such cases, the browser has to decide which style to apply to the element. In this article, we'll understand what causes conflicting styles in CSS, and how to avoid and resolve them. Causes of Confl
4 min read
How to Handle Big Repositories With Git?
Git is a free and open-source distributed version control system designed to handle everything from small to very large projects with speed and efficiency. Git relies on the basis of distributed development of software where more than one developer may have access to the source code of a specific application and can modify changes to it that may be
3 min read
How Does Git Handle Symbolic Links?
Git, the widely used version control system, is known for its ability to manage files and directories efficiently. One of the lesser-discussed but equally important features of Git is its support for symbolic links (symlinks). Symbolic links are a type of file that acts as pointers to another file or directory. In this article, we will see how Git
3 min read
Difference Between Git Fetch and Git Pull
Understanding the difference between git fetch and git pull is important for effective version control in Git. These commands are important for managing your repository and collaborating with team members. In this article, Let us look at Git Fetch and Git Pull separately with the help of an example. What is Git Fetch?The Git Fetch command is used t
4 min read
Difference Between Git Push Origin and Git Push Origin Master
Understanding the difference between git push origin and git push origin master is important for efficient version control in Git. These commands are used to upload changes from your local repository to a remote repository, but they function differently. This article will explain these differences, how each command works, and when to use them. What
3 min read
Difference between “git add -A” and “git add”
When working with Git, the git add command is used to move changes from your working directory to the staging area. However, there are different options and flags that can be used with git add, such as -A, which might lead to some confusion. In this article, we'll explore the differences between git add -A and git add. 1. Git add- CommandThe git ad
2 min read
Git - Difference Between Git Revert, Checkout and Reset
Git offers a range of commands to manage and manipulate your codebase. Among these commands, git revert, git checkout, and git reset are frequently used for different purposes. Understanding the differences between these commands is important for effective version control. In this article, we'll explore the functionalities and use cases of git reve
6 min read
Difference Between "git commit" and "git push"?
Git commit and git push are two essential commands you'll use a lot when working with Git. even their frequent use together, they have different functions. In order to help you understand when and how to use these two commands effectively in your version control workflow, this article will break down their differences. What is git commit?git commit
2 min read
How to Resolve "Commit Your Changes or Stash Them Before You Can Merge"?
When working with Git, you may encounter the message: "Commit your changes or stash them before you can merge." This message indicates that you have uncommitted changes in your working directory, and Git won't allow you to proceed with a merge, pull, or checkout operation until those changes are addressed. Here's how to resolve this situation effec
2 min read
Git - git-show Command Line Utility
Git is a free and open-source distributed version control system designed to handle everything from small to very large projects with speed and efficiency. Git relies on the basis of distributed development of software where more than one developer may have access to the source code of a specific application and can modify changes to it that may be
3 min read
Git LFS: Managing Large Files in Git Repositories
Git, undoubtedly one of the most popular version control systems, is widely used for managing source code in software development projects. However, one of its limitations is its handling of large files. Traditional Git repositories struggle to efficiently manage large files, leading to bloated repositories and slow performance. This is where Git L
4 min read
Git Subtree vs. Git Submodule
Git Subtree and Git Submodule are both mechanisms in Git that allow you to incorporate external repositories into your own repository. They provide a way to manage dependencies and include code from other projects while keeping your repository organized and maintainable. Git Subtree: Git Subtree allows you to insert a separate repository as a subdi
4 min read
How to Set Up Git Using Git Config?
Git is a powerful version control system that helps developers manage and track changes in their code. Setting up Git correctly is important for maintaining an organized and efficient workflow. In this article, we'll walk you through the process of setting up Git using the git config command. PrerequisitesBefore we dive into the setup process, make
3 min read
How To Exit Git Log or Git Diff?
When working with Git, the git log and git diff commands are important for viewing commit history and changes between commits, respectively. However, if you're new to Git, you might find yourself stuck in these views, unsure how to exit. This article will guide you through the steps to exit git log or git diff, ensuring a smooth experience while na
2 min read
Git - git prune
Git is a powerful version control system that helps developers manage their code efficiently. However, as your project evolves, you may accumulate unnecessary data that clutters your repository. This is where git prune comes in view. What is git prune?git prune is a Git command that removes objects that are no longer referenced by any branch or tag
5 min read
How to Fix Git Error "Unable to create '/path/my_project/.git/index.lock'"?
The Git error "Unable to create '/path/my_project/.git/index.lock'" typically occurs when Git is unable to create or write to the index.lock file. This file is used to prevent simultaneous processes from modifying the repository, which could lead to corruption. Table of Content Remove the Lock File ManuallyUse Git Command to Remove the Lock FileRes
2 min read
Git-Checkout And Merge
Git is an important tool for software development, helping teams to manage code changes and collaborate effectively. Among its many commands, git checkout and git merge are important for handling branches. This article provides a detailed guide on using these commands to streamline your workflow. What is git checkout?The git checkout is a navigator
4 min read
How to Merge Two Branches in Git?
Version control systems like Git provide powerful tools for managing code changes and collaboration among developers. One common task in Git is merging branches, which allows you to combine the changes made in one branch into another. In this article, we will explore the process of merging branches in Git. PrerequisitesGitHub Desktop installedAn ac
4 min read
How to abort merge in Git ?
In collaborative coding environments, Git's merge feature is invaluable for integrating changes from different branches. However, there are times when a merge operation encounters conflicts or isn't proceeding as expected, necessitating an abort. This article explores how to effectively abort a merge in Git, ensuring a smooth development workflow.
3 min read
How to Merge a Git Branch into Master?
If you're working with Git, merging branches is a fundamental task. Whether you're adding new features, fixing bugs, or improving documentation, merging ensures that your changes are integrated into the main codebase. In this guide, we'll walk you through the process of merging a Git branch into the master, which helps your codebase remain up-to-da
3 min read
How to Merge Commits in Git?
Merging commits in Git is a crucial part of version control, especially when working on complex projects with multiple contributors. Combining commits can help streamline the commit history, making it cleaner and easier to understand. In this article, we’ll explore different methods to merge commits in Git effectively. Why Merge Commits?Before divi
3 min read
How to Fix - Git Refusing to Merge Unrelated Histories on Rebase?
When working with Git, you might encounter the error "refusing to merge unrelated histories" during a rebase. This error occurs when Git detects that the branches you're trying to rebase do not share a common commit, which can happen for various reasons, such as merging branches from different repositories or when initializing a new repository with
3 min read
How to Merge Unrelated Histories in Git?
Merging unrelated histories in Git might seem a difficult task, but it’s a common task that arises in various scenarios. Unrelated histories occur when two branches or repositories do not share a common commit ancestor, which can happen when combining projects, integrating different repositories, or starting fresh with new histories. This article w
3 min read
How to Merge two Git Repositories?
Merging two Git repositories can be a complex task, especially if they have distinct histories, branches, and commit structures. This guide explores different approaches and details each step involved in merging two Git repositories. Merge One Repository as a Subtree of AnotherThis approach involves adding one repository as a subdirectory within an
1 min read
How to Revert a Pushed Merge Commit in Git?
In Git, merge commits are created when integrating changes from one branch into another. Sometimes, you may find yourself in a situation where you need to revert a merge commit that has already been pushed to a remote repository. Reverting a merge commit requires careful consideration to maintain the integrity of the project history. In this articl
3 min read
How to Fix Git “Refusing to Merge Unrelated Histories”?
When working with Git, you might encounter an error message saying "refusing to merge unrelated histories" when you try to merge branches or pull changes. This error typically occurs when you attempt to merge two branches or repositories that do not share a common commit history. In this article, we'll explore why this happens and how to resolve it
2 min read
Article Tags :
three90RightbarBannerImg