For those of you who use some form of version control, merge conflicts are familiar. Git is exceptional at auto-merging conflicts. However, there are some cases in which Git is unable to determine what needs to be done automatically. In that situation a manual merge is needed. Even though it may seem difficult at times, Git provides numerous useful methods to assist with difficult merges. Options such as “ours” and “theirs” allow us to inform Git on what strategy to use when working to merge conflict so that is does not have to be done manually.

As an example, assume that we have a branch, branchA, that has deviated from the master branch. BranchA is apart from the master branch and therefore both branchA and the master branch have both made amendments to the exact same line of the same file. This produces a problem where Git cannot solve the merge conflicts for us.

Resolve Merge Conflicts with Git

In most cases, solutions to merge-conflicts are as simple as removing local changes or remote branch changes. In these cases, it is useful to do as follows:

  • Discover files with merge conflict
    • Change working directory to project folder: cd project-folder
    • Search for all conflicting files:

      grep -lr ‘<<<<<<<‘ .

  • Resolve easy conflicts by:
    • When getting to this point, you may review each file. If the solution is to accept local/our version, run:

      git checkout –ours PATH/FILE

    • If solution is to accept remote/other-branch version, run:

      git checkout –theirs PATH/FILE

    • If there are multiple files and you want to accept local/our version, run:

      grep -lr ‘<<<<<<<‘ . | xargs git checkout –ours

    • If you have many files and you want to accept remote/other-branch version, run:

      grep -lr ‘<<<<<<<‘ . | xargs git checkout –theirs

  • Complex merge conflicts:
    • For files that needs manual review/edit, use vim or any text editor to fix the differences
    • Be sure to run Git by adding FILENAME for files edited using vim
    • Lastly be sure to review if all files are ready for commit using Git status