Browse topics

git merge

Version
2.51
Review
Draft

Summary#

git merge joins another history into the current branch. When the current branch is behind the branch being merged, Git normally fast-forwards. Use --no-ff to record a merge commit when a fast-forward is possible, --ff-only to reject divergence, and --abort to cancel a merge in progress.

Syntax#

sh
git merge topic
git merge --no-ff topic
git merge --ff-only topic
git merge --no-overwrite-ignore topic
git merge --continue
git merge --abort

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_PAGER=cat 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 'hello\n' > greeting.txt
  git add greeting.txt
  git commit -qm "Add greeting"

  git switch -q -c formal
  printf 'good day\n' > greeting.txt
  git commit -qam "Use formal greeting"
  git switch -q trunk
  printf 'hi\n' > greeting.txt
  git commit -qam "Use short greeting"

  if ! git merge formal > /dev/null 2>&1; then echo "merge stopped"; fi
  git status --short
  git merge --abort
  cat greeting.txt

  git switch -q -c docs
  printf 'notes\n' > notes.txt
  git add notes.txt
  git commit -qm "Add notes"
  git switch -q trunk
  git merge -q --no-ff -m "Merge docs" docs
  git log -1 --format=%s
  echo "parents: $(git cat-file -p HEAD | grep -c '^parent ')"
)

Expected output#

Text
merge stopped
UU greeting.txt
hi
Merge docs
parents: 2

Common mistakes#

-X ours and -s ours are different. The first prefers your side in conflicting hunks while still taking nonconflicting changes from the other side. The second discards every change from the other branch while recording it as merged. Commit or stash before merging, because --abort cannot always reconstruct uncommitted changes. Use --no-overwrite-ignore to stop a merge that would overwrite an ignored file.

Version applicability#

Git 1.6.6 added --ff-only, Git 1.7.4 added --abort, Git 1.7.9 added --no-overwrite-ignore, and Git 2.12 added --continue. Git 2.34 made ort the default merge strategy in place of recursive.

The complete example requires Git 2.28 or later for git init -b.

Sources#

Attribution
DevLookup contributors
License
CC-BY-4.0