Browse topics

Resolve Git merge conflicts

Version
2.51
Review
Draft

Summary#

When a merge stops, list the unmerged paths. In the default text conflict style, the lines after <<<<<<< are from your current branch, and the lines after ======= are from the branch you're merging. Edit the file to the intended result, remove the markers, then stage the resolution.

Syntax#

sh
git diff --name-only --diff-filter=U
# Edit the conflicting file, then stage and review the result.
git add -- path/to/file
git diff --staged --check
git diff --staged -- path/to/file
git merge --continue

Example#

sh
(
  set -eu
  scratch=$(mktemp -d "${TMPDIR:-/tmp}/devlookup-git.XXXXXX")
  trap 'rm -rf -- "$scratch"' EXIT
  unset GIT_CONFIG_GLOBAL $(git rev-parse --local-env-vars)
  export GIT_CONFIG_NOSYSTEM=1 GIT_TEMPLATE_DIR= LC_ALL=C
  export HOME="$scratch" XDG_CONFIG_HOME="$scratch" GIT_ATTR_NOSYSTEM=1
  export GIT_EDITOR=true
  mkdir "$scratch/work"
  cd "$scratch/work"
  git init -q -b trunk
  git config user.name "Reference Example"
  git config user.email example@example.invalid
  printf 'timeout=5\n' > service.conf
  git add -- service.conf
  git commit -qm "Set default timeout"
  git switch -qc tuning
  printf 'timeout=15\n' > service.conf
  git commit -qam "Allow slower connections"
  git switch -q trunk
  printf 'timeout=10\n' > service.conf
  git commit -qam "Raise the default"

  if git merge tuning > /dev/null 2>&1; then exit 1; fi
  git diff --name-only --diff-filter=U
  cat service.conf
  printf 'timeout=12\n' > service.conf
  git add -- service.conf
  git diff --staged --check
  git diff --staged -- service.conf | sed -n '/^+timeout=/p'
  git merge --continue > /dev/null
  git show HEAD:service.conf
)

Expected output#

Text
service.conf
<<<<<<< HEAD
timeout=10
=======
timeout=15
>>>>>>> tuning
+timeout=12
timeout=12

Common mistakes#

CONFLICT (content): Merge conflict in path followed by Automatic merge failed; fix conflicts and then commit the result. means that Git stopped the merge for you to resolve that file. To return to the state before the merge, run git merge --abort, which can fail to restore changes that were uncommitted when the merge started.

Stage each file after editing. For a resolution that deletes a conflicted file, use git rm on the path. git diff --staged --check catches newly added conflict markers and whitespace errors. Review the staged diff for correctness. If you were rebasing, resume with git rebase --continue.

Version applicability#

Git 2.12 added git merge --continue. On earlier versions, finish a resolved merge with git commit. The complete example requires Git 2.28 or later for git init -b.

Sources#

Attribution
DevLookup contributors
License
CC-BY-4.0