How to resolve git conflicts

Conflicts in git may arise whenever one commit is applied onto the changes from another that is not its immediate predecessor. This includes when using git rebase, git merge, and git cherry-pick (to name the most obvious contexts), but conflicts might occur in other situations, as well.

When there are conflicts, you will see something like “both modified” on certain files when you do git status. In these cases, git has taken the bits of the file it couldn’t figure out how to reconcile, and marked them up for you to review. You will find <<<<, ====, and >>>> markings in the files that show where two or more lines were changed independently in both commits.

Take the following general steps to resolve the conflicts:

  1. Edit the files in question, remove the markup and replace with just the lines that should be present in the commit (hint: you can also use the shortcut described below)
  2. Use git add to stage the edited files for commit
  3. Use the --continue flag on the command you were running when you got the conflicts. For example git rebase --continue, git merge --continue, or git cherry-pick --continue

Shortcut

When you run git diff to view your conflicts, you may find that you want to keep all of one and none of the other of the conflicting sections. In that case, you can use git checkout --theirs or git checkout --ours instead of editing the file(s) before using git add. This will remove the conflict markers from the file and keep only the specified section.

Here is a rule of thumb for which to use:

Flag What it refers to
--ours The commit labeled with HEAD in the diff, shown above the other commit in the diff
--theirs The commit labeled with a commit id, shown below the other commit in the diff

The changes tagged with HEAD at the top are from the current commit, and the changes below, usually marked with the commit id of the incoming commit, are the commit that is being applied.

Keep in mind that, when merging, the HEAD commit represents your current commit. When rebasing, the branch HEAD is rewound to the highest common commit, and then each commit in the rebase is applied in sequence. So in that case, usually the HEAD is the “other” commit, and the section below with the commit ID is your own commit that you are applying onto that.