Resolving conflicts when merging branches

Merge conflicts occur when git is unable to automatically merge changes from different branches. This happens when there are conflicting changes in the same places in the repository.

The causes of conflicts may include:

  • Multiple users editing the same files at once.
  • Pulling remote repository changes (git pull) that conflict with your local edits.
  • Merging branches (git merge) with conflicting changes made to the same lines of code.
  • Pushing changes (git push) to the remote repository that has commits conflicting with your local edits.

Types of conflicts:

  • Line update conflicts are the most common type of conflict, which occurs when the same file line is updated differently in different branches.
  • File structure conflicts occur when one user updates a file and another user deletes it.

What conflicts look like in files

When git detects a conflict, it marks the problematic sections with special markers:

Common part of the text before the conflict
<<<<<<< HEAD
Changes in the current branch
=======
Changes in the incomning branch
>>>>>>> branch-name

Where:

  • <<<<<<< HEAD marks the beginning of changes in the current branch.
  • ======= is the separator between versions.
  • >>>>>>> branch-name marks the end of changes in the incoming branch.

Resolving conflicts from the command line

To resolve a conflict using the command line:

  1. Identify the files with conflicts by executing this command:

    git status
    

    Files with conflicts will be displayed marked with both modified.

  2. Open the file with the conflict in the text editor.

  3. Locate the conflict markers (<<<<<<<, =======, >>>>>>>).

  4. Choose the conflict resolution option:

    • Delete the version you do not need.
    • Create new code to merge both versions.

    After the changes are introduced, remove all conflict markers.

  5. Save the file.

  6. Add the updated file into the index:

    git add <file_name>
    
  7. Finish the merge:

    git commit -m "Resolve merge conflict"
    
  8. Push the changes:

    git push
    

File structure conflicts

To resolve a conflict when a file was updated in one branch and deleted in another:

  1. Check the conflict status:

    git status
    
  2. Choose the next action with the file:

    • To keep the file, run this command:

      git add <file_name>
      
    • To delete the file, run this command:

      git rm <file_name>
      
  3. Finish the merge:

    git commit -m "Resolve file deletion conflict"
    

Using merge tools

You can use graphical tools for convenient conflict resolution.
To start the configured merge tool, such as VS Code, Sublime Merge, or others, run this command:

git mergetool

Aborting the merge

To abort the merge and revert to the state before the operation started, run this command:

git merge --abort

See also