NAME

git-merge - Join two or more development histories together

SYNOPSIS

  1. git merge [-n] [--stat] [--no-commit] [--squash] [--[no-]edit]
  2. [-s <strategy>] [-X <strategy-option>] [-S[<keyid>]]
  3. [--[no-]allow-unrelated-histories]
  4. [--[no-]rerere-autoupdate] [-m <msg>] [-F <file>] [<commit>…​]
  5. git merge (--continue | --abort | --quit)

DESCRIPTION

Incorporates changes from the named commits (since the time theirhistories diverged from the current branch) into the currentbranch. This command is used by git pull to incorporate changesfrom another repository and can be used by hand to merge changesfrom one branch into another.

Assume the following history exists and the current branch is"master":

  1. A---B---C topic
  2. /
  3. D---E---F---G master

Then "git merge topic" will replay the changes made on thetopic branch since it diverged from master (i.e., E) untilits current commit (C) on top of master, and record the resultin a new commit along with the names of the two parent commits anda log message from the user describing the changes.

  1. A---B---C topic
  2. / \
  3. D---E---F---G---H master

The second syntax ("git merge —abort") can only be run after themerge has resulted in conflicts. git merge —abort will abort themerge process and try to reconstruct the pre-merge state. However,if there were uncommitted changes when the merge started (andespecially if those changes were further modified after the mergewas started), git merge —abort will in some cases be unable toreconstruct the original (pre-merge) changes. Therefore:

Warning: Running git merge with non-trivial uncommitted changes isdiscouraged: while possible, it may leave you in a state that is hard toback out of in the case of a conflict.

The third syntax ("git merge —continue") can only be run after themerge has resulted in conflicts.

OPTIONS

  • —commit
  • —no-commit
  • Perform the merge and commit the result. This option canbe used to override —no-commit.

With —no-commit perform the merge and stop just before creatinga merge commit, to give the user a chance to inspect and furthertweak the merge result before committing.

Note that fast-forward updates do not create a merge commit andtherefore there is no way to stop those merges with —no-commit.Thus, if you want to ensure your branch is not changed or updatedby the merge command, use —no-ff with —no-commit.

  • —edit
  • -e
  • —no-edit
  • Invoke an editor before committing successful mechanical merge tofurther edit the auto-generated merge message, so that the usercan explain and justify the merge. The —no-edit option can beused to accept the auto-generated message (this is generallydiscouraged).The —edit (or -e) option is still useful if you aregiving a draft message with the -m option from the command lineand want to edit it in the editor.

Older scripts may depend on the historical behaviour of not allowing theuser to edit the merge log message. They will see an editor opened whenthey run git merge. To make it easier to adjust such scripts to theupdated behaviour, the environment variable GIT_MERGE_AUTOEDIT can beset to no at the beginning of them.

  • —cleanup=
  • This option determines how the merge message will be cleaned up beforecommiting. See git-commit[1] for more details. In addition, ifthe is given a value of scissors, scissors will be appendedto MERGE_MSG before being passed on to the commit machinery in thecase of a merge conflict.

  • —ff

  • When the merge resolves as a fast-forward, only update the branchpointer, without creating a merge commit. This is the defaultbehavior.

  • —no-ff

  • Create a merge commit even when the merge resolves as afast-forward. This is the default behaviour when merging anannotated (and possibly signed) tag that is not stored inits natural place in refs/tags/ hierarchy.

  • —ff-only

  • Refuse to merge and exit with a non-zero status unless thecurrent HEAD is already up to date or the merge can beresolved as a fast-forward.

  • -S[]

  • —gpg-sign[=]
  • GPG-sign the resulting merge commit. The keyid argument isoptional and defaults to the committer identity; if specified,it must be stuck to the option without a space.

  • —log[=]

  • —no-log
  • In addition to branch names, populate the log message withone-line descriptions from at most actual commits that are beingmerged. See also git-fmt-merge-msg[1].

With —no-log do not list one-line descriptions from theactual commits being merged.

  • —signoff
  • —no-signoff
  • Add Signed-off-by line by the committer at the end of the commitlog message. The meaning of a signoff depends on the project,but it typically certifies that committer hasthe rights to submit this work under the same license andagrees to a Developer Certificate of Origin(see http://developercertificate.org/ for more information).

With —no-signoff do not add a Signed-off-by line.

  • —stat
  • -n
  • —no-stat
  • Show a diffstat at the end of the merge. The diffstat is alsocontrolled by the configuration option merge.stat.

With -n or —no-stat do not show a diffstat at the end of themerge.

  • —squash
  • —no-squash
  • Produce the working tree and index state as if a real mergehappened (except for the merge information), but do not actuallymake a commit, move the HEAD, or record $GIT_DIR/MERGE_HEAD(to cause the next git commit command to create a mergecommit). This allows you to create a single commit on top ofthe current branch whose effect is the same as merging anotherbranch (or more in case of an octopus).

With —no-squash perform the merge and commit the result. Thisoption can be used to override —squash.

With —squash, —commit is not allowed, and will fail.

  • -s
  • —strategy=
  • Use the given merge strategy; can be supplied more thanonce to specify them in the order they should be tried.If there is no -s option, a built-in list of strategiesis used instead (git merge-recursive when merging a singlehead, git merge-octopus otherwise).

  • -X

  • —strategy-option=
  • Pass merge strategy specific option through to the mergestrategy.

  • —verify-signatures

  • —no-verify-signatures
  • Verify that the tip commit of the side branch being merged issigned with a valid key, i.e. a key that has a valid uid: in thedefault trust model, this means the signing key has been signed bya trusted key. If the tip commit of the side branch is not signedwith a valid key, the merge is aborted.

  • —summary

  • —no-summary
  • Synonyms to —stat and —no-stat; these are deprecated and will beremoved in the future.

  • -q

  • —quiet
  • Operate quietly. Implies —no-progress.

  • -v

  • —verbose
  • Be verbose.

  • —progress

  • —no-progress
  • Turn progress on/off explicitly. If neither is specified,progress is shown if standard error is connected to a terminal.Note that not all merge strategies may support progressreporting.

  • —allow-unrelated-histories

  • By default, git merge command refuses to merge historiesthat do not share a common ancestor. This option can beused to override this safety when merging histories of twoprojects that started their lives independently. As that isa very rare occasion, no configuration variable to enablethis by default exists and will not be added.

  • -m

  • Set the commit message to be used for the merge commit (incase one is created).

If —log is specified, a shortlog of the commits being mergedwill be appended to the specified message.

The git fmt-merge-msg command can beused to give a good default for automated _git merge_invocations. The automated message can include the branch description.

  • -F
  • —file=
  • Read the commit message to be used for the merge commit (incase one is created).

If —log is specified, a shortlog of the commits being mergedwill be appended to the specified message.

  • —rerere-autoupdate
  • —no-rerere-autoupdate
  • Allow the rerere mechanism to update the index with theresult of auto-conflict resolution if possible.

  • —overwrite-ignore

  • —no-overwrite-ignore
  • Silently overwrite ignored files from the merge result. Thisis the default behavior. Use —no-overwrite-ignore to abort.

  • —abort

  • Abort the current conflict resolution process, andtry to reconstruct the pre-merge state.

If there were uncommitted worktree changes present when the mergestarted, git merge —abort will in some cases be unable toreconstruct these changes. It is therefore recommended to alwayscommit or stash your changes before running git merge.

git merge —abort is equivalent to git reset —merge whenMERGE_HEAD is present.

  • —quit
  • Forget about the current merge in progress. Leave the indexand the working tree as-is.

  • —continue

  • After a git merge stops due to conflicts you can conclude themerge by running git merge —continue (see "HOW TO RESOLVECONFLICTS" section below).

  • …​

  • Commits, usually other branch heads, to merge into our branch.Specifying more than one commit will create a merge withmore than two parents (affectionately called an Octopus merge).

If no commit is given from the command line, merge the remote-trackingbranches that the current branch is configured to use as its upstream.See also the configuration section of this manual page.

When FETCH_HEAD (and no other commit) is specified, the branchesrecorded in the .git/FETCH_HEAD file by the previous invocationof git fetch for merging are merged to the current branch.

PRE-MERGE CHECKS

Before applying outside changes, you should get your own work ingood shape and committed locally, so it will not be clobbered ifthere are conflicts. See also git-stash[1].git pull and git merge will stop without doing anything whenlocal uncommitted changes overlap with files that git pull/gitmerge may need to update.

To avoid recording unrelated changes in the merge commit,git pull and git merge will also abort if there are any changesregistered in the index relative to the HEAD commit. (Specialnarrow exceptions to this rule may exist depending on which mergestrategy is in use, but generally, the index must match HEAD.)

If all named commits are already ancestors of HEAD, _git merge_will exit early with the message "Already up to date."

FAST-FORWARD MERGE

Often the current branch head is an ancestor of the named commit.This is the most common case especially when invoked from gitpull: you are tracking an upstream repository, you have committedno local changes, and now you want to update to a newer upstreamrevision. In this case, a new commit is not needed to store thecombined history; instead, the HEAD (along with the index) isupdated to point at the named commit, without creating an extramerge commit.

This behavior can be suppressed with the —no-ff option.

TRUE MERGE

Except in a fast-forward merge (see above), the branches to bemerged must be tied together by a merge commit that has both of themas its parents.

A merged version reconciling the changes from all branches to bemerged is committed, and your HEAD, index, and working tree areupdated to it. It is possible to have modifications in the workingtree as long as they do not overlap; the update will preserve them.

When it is not obvious how to reconcile the changes, the followinghappens:

  • The HEAD pointer stays the same.

  • The MERGE_HEAD ref is set to point to the other branch head.

  • Paths that merged cleanly are updated both in the index file andin your working tree.

  • For conflicting paths, the index file records up to threeversions: stage 1 stores the version from the common ancestor,stage 2 from HEAD, and stage 3 from MERGE_HEAD (youcan inspect the stages with git ls-files -u). The workingtree files contain the result of the "merge" program; i.e. 3-waymerge results with familiar conflict markers <<< === >>>.

  • No other changes are made. In particular, the localmodifications you had before you started merge will stay thesame and the index entries for them stay as they were,i.e. matching HEAD.

If you tried a merge which resulted in complex conflicts andwant to start over, you can recover with git merge —abort.

MERGING TAG

When merging an annotated (and possibly signed) tag, Git alwayscreates a merge commit even if a fast-forward merge is possible, andthe commit message template is prepared with the tag message.Additionally, if the tag is signed, the signature check is reportedas a comment in the message template. See also git-tag[1].

When you want to just integrate with the work leading to the committhat happens to be tagged, e.g. synchronizing with an upstreamrelease point, you may not want to make an unnecessary merge commit.

In such a case, you can "unwrap" the tag yourself before feeding itto git merge, or pass —ff-only when you do not have any work onyour own. e.g.

  1. git fetch origin
  2. git merge v1.2.3^0
  3. git merge --ff-only v1.2.3

HOW CONFLICTS ARE PRESENTED

During a merge, the working tree files are updated to reflect the resultof the merge. Among the changes made to the common ancestor’s version,non-overlapping ones (that is, you changed an area of the file while theother side left that area intact, or vice versa) are incorporated in thefinal result verbatim. When both sides made changes to the same area,however, Git cannot randomly pick one side over the other, and asks you toresolve it by leaving what both sides did to that area.

By default, Git uses the same style as the one used by the "merge" programfrom the RCS suite to present such a conflicted hunk, like this:

  1. Here are lines that are either unchanged from the common
  2. ancestor, or cleanly resolved because only one side changed.
  3. <<<<<<< yours:sample.txt
  4. Conflict resolution is hard;
  5. let's go shopping.
  6. =======
  7. Git makes conflict resolution easy.
  8. >>>>>>> theirs:sample.txt
  9. And here is another line that is cleanly resolved or unmodified.

The area where a pair of conflicting changes happened is marked with markers<<<<<<<, =======, and >>>>>>>. The part before the =======is typically your side, and the part afterwards is typically their side.

The default format does not show what the original said in the conflictingarea. You cannot tell how many lines are deleted and replaced withBarbie’s remark on your side. The only thing you can tell is that yourside wants to say it is hard and you’d prefer to go shopping, while theother side wants to claim it is easy.

An alternative style can be used by setting the "merge.conflictStyle"configuration variable to "diff3". In "diff3" style, the above conflictmay look like this:

  1. Here are lines that are either unchanged from the common
  2. ancestor, or cleanly resolved because only one side changed.
  3. <<<<<<< yours:sample.txt
  4. Conflict resolution is hard;
  5. let's go shopping.
  6. |||||||
  7. Conflict resolution is hard.
  8. =======
  9. Git makes conflict resolution easy.
  10. >>>>>>> theirs:sample.txt
  11. And here is another line that is cleanly resolved or unmodified.

In addition to the <<<<<<<, =======, and >>>>>>> markers, it usesanother ||||||| marker that is followed by the original text. You cantell that the original just stated a fact, and your side simply gave in tothat statement and gave up, while the other side tried to have a morepositive attitude. You can sometimes come up with a better resolution byviewing the original.

HOW TO RESOLVE CONFLICTS

After seeing a conflict, you can do two things:

  • Decide not to merge. The only clean-ups you need are to resetthe index file to the HEAD commit to reverse 2. and to cleanup working tree changes made by 2. and 3.; git merge —abortcan be used for this.

  • Resolve the conflicts. Git will mark the conflicts inthe working tree. Edit the files into shape andgit add them to the index. Use git commit orgit merge —continue to seal the deal. The latter commandchecks whether there is a (interrupted) merge in progressbefore calling git commit.

You can work through the conflict with a number of tools:

  • Use a mergetool. git mergetool to launch a graphicalmergetool which will work you through the merge.

  • Look at the diffs. git diff will show a three-way diff,highlighting changes from both the HEAD and MERGE_HEADversions.

  • Look at the diffs from each branch. git log —merge -p <path>will show diffs first for the HEAD version and then theMERGE_HEAD version.

  • Look at the originals. git show :1:filename shows thecommon ancestor, git show :2:filename shows the HEADversion, and git show :3:filename shows the MERGE_HEADversion.

EXAMPLES

  • Merge branches fixes and enhancements on top ofthe current branch, making an octopus merge:
  1. $ git merge fixes enhancements
  • Merge branch obsolete into the current branch, using oursmerge strategy:
  1. $ git merge -s ours obsolete
  • Merge branch maint into the current branch, but do not makea new commit automatically:
  1. $ git merge --no-commit maint

This can be used when you want to include further changes to themerge, or want to write your own merge commit message.

You should refrain from abusing this option to sneak substantialchanges into a merge commit. Small fixups like bumpingrelease/version name would be acceptable.

MERGE STRATEGIES

The merge mechanism (git merge and git pull commands) allows thebackend merge strategies to be chosen with -s option. Some strategiescan also take their own options, which can be passed by giving -X<option>arguments to git merge and/or git pull.

  • resolve
  • This can only resolve two heads (i.e. the current branchand another branch you pulled from) using a 3-way mergealgorithm. It tries to carefully detect criss-crossmerge ambiguities and is considered generally safe andfast.

  • recursive

  • This can only resolve two heads using a 3-way mergealgorithm. When there is more than one commonancestor that can be used for 3-way merge, it creates amerged tree of the common ancestors and uses that asthe reference tree for the 3-way merge. This has beenreported to result in fewer merge conflicts withoutcausing mismerges by tests done on actual merge commitstaken from Linux 2.6 kernel development history.Additionally this can detect and handle merges involvingrenames, but currently cannot make use of detectedcopies. This is the default merge strategy when pullingor merging one branch.

The recursive strategy can take the following options:

  • ours
  • This option forces conflicting hunks to be auto-resolved cleanly byfavoring our version. Changes from the other tree that do notconflict with our side are reflected to the merge result.For a binary file, the entire contents are taken from our side.

This should not be confused with the ours merge strategy, which does noteven look at what the other tree contains at all. It discards everythingthe other tree did, declaring our history contains all that happened in it.

  • theirs
  • This is the opposite of ours; note that, unlike ours, there isno theirs merge strategy to confuse this merge option with.

  • patience

  • With this option, merge-recursive spends a little extra timeto avoid mismerges that sometimes occur due to unimportantmatching lines (e.g., braces from distinct functions). Usethis when the branches to be merged have diverged wildly.See also git-diff[1] —patience.

  • diff-algorithm=[patience|minimal|histogram|myers]

  • Tells merge-recursive to use a different diff algorithm, whichcan help avoid mismerges that occur due to unimportant matchinglines (such as braces from distinct functions). See alsogit-diff[1] —diff-algorithm.

  • ignore-space-change

  • ignore-all-space
  • ignore-space-at-eol
  • ignore-cr-at-eol
  • Treats lines with the indicated type of whitespace change asunchanged for the sake of a three-way merge. Whitespacechanges mixed with other changes to a line are not ignored.See also git-diff[1] -b, -w,—ignore-space-at-eol, and —ignore-cr-at-eol.
  1. -

If their version only introduces whitespace changes to a line,our version is used;

  1. -

If our version introduces whitespace changes but their_version includes a substantial change, _their version is used;

  1. -

Otherwise, the merge proceeds in the usual way.

  • renormalize
  • This runs a virtual check-out and check-in of all three stagesof a file when resolving a three-way merge. This option ismeant to be used when merging branches with different cleanfilters or end-of-line normalization rules. See "Mergingbranches with differing checkin/checkout attributes" ingitattributes[5] for details.

  • no-renormalize

  • Disables the renormalize option. This overrides themerge.renormalize configuration variable.

  • no-renames

  • Turn off rename detection. This overrides the merge.renamesconfiguration variable.See also git-diff[1] —no-renames.

  • find-renames[=]

  • Turn on rename detection, optionally setting the similaritythreshold. This is the default. This overrides themerge.renames configuration variable.See also git-diff[1] —find-renames.

  • rename-threshold=

  • Deprecated synonym for find-renames=<n>.

  • subtree[=]

  • This option is a more advanced form of subtree strategy, wherethe strategy makes a guess on how two trees must be shifted tomatch with each other when merging. Instead, the specified pathis prefixed (or stripped from the beginning) to make the shape oftwo trees to match.
  • octopus
  • This resolves cases with more than two heads, but refuses to doa complex merge that needs manual resolution. It isprimarily meant to be used for bundling topic branchheads together. This is the default merge strategy whenpulling or merging more than one branch.

  • ours

  • This resolves any number of heads, but the resulting tree of themerge is always that of the current branch head, effectivelyignoring all changes from all other branches. It is meant tobe used to supersede old development history of sidebranches. Note that this is different from the -Xours option tothe recursive merge strategy.

  • subtree

  • This is a modified recursive strategy. When merging trees A andB, if B corresponds to a subtree of A, B is first adjusted tomatch the tree structure of A, instead of reading the trees atthe same level. This adjustment is also done to the commonancestor tree.

With the strategies that use 3-way merge (including the default, recursive),if a change is made on both branches, but later reverted on one of thebranches, that change will be present in the merged result; some people findthis behavior confusing. It occurs because only the heads and the merge baseare considered when performing a merge, not the individual commits. The mergealgorithm therefore considers the reverted change as no change at all, andsubstitutes the changed version instead.

CONFIGURATION

  • merge.conflictStyle
  • Specify the style in which conflicted hunks are written out toworking tree files upon merge. The default is "merge", whichshows a <<<<<<< conflict marker, changes made by one side,a ======= marker, changes made by the other side, and thena >>>>>>> marker. An alternate style, "diff3", adds a |||||||marker and the original text before the ======= marker.

  • merge.defaultToUpstream

  • If merge is called without any commit argument, merge the upstreambranches configured for the current branch by using their lastobserved values stored in their remote-tracking branches.The values of the branch.<current branch>.merge that name thebranches at the remote named by branch.<current branch>.remoteare consulted, and then they are mapped via remote.<remote>.fetchto their corresponding remote-tracking branches, and the tips ofthese tracking branches are merged.

  • merge.ff

  • By default, Git does not create an extra merge commit when merginga commit that is a descendant of the current commit. Instead, thetip of the current branch is fast-forwarded. When set to false,this variable tells Git to create an extra merge commit in sucha case (equivalent to giving the —no-ff option from the commandline). When set to only, only such fast-forward merges areallowed (equivalent to giving the —ff-only option from thecommand line).

  • merge.verifySignatures

  • If true, this is equivalent to the —verify-signatures commandline option. See git-merge[1] for details.

  • merge.branchdesc

  • In addition to branch names, populate the log message withthe branch description text associated with them. Defaultsto false.

  • merge.log

  • In addition to branch names, populate the log message with atmost the specified number of one-line descriptions from theactual commits that are being merged. Defaults to false, andtrue is a synonym for 20.

  • merge.renameLimit

  • The number of files to consider when performing rename detectionduring a merge; if not specified, defaults to the value ofdiff.renameLimit. This setting has no effect if rename detectionis turned off.

  • merge.renames

  • Whether Git detects renames. If set to "false", rename detectionis disabled. If set to "true", basic rename detection is enabled.Defaults to the value of diff.renames.

  • merge.directoryRenames

  • Whether Git detects directory renames, affecting what happens atmerge time to new files added to a directory on one side ofhistory when that directory was renamed on the other side ofhistory. If merge.directoryRenames is set to "false", directoryrename detection is disabled, meaning that such new files will beleft behind in the old directory. If set to "true", directoryrename detection is enabled, meaning that such new files will bemoved into the new directory. If set to "conflict", a conflictwill be reported for such paths. If merge.renames is false,merge.directoryRenames is ignored and treated as false. Defaultsto "conflict".

  • merge.renormalize

  • Tell Git that canonical representation of files in therepository has changed over time (e.g. earlier commits recordtext files with CRLF line endings, but recent ones use LF lineendings). In such a repository, Git can convert the datarecorded in commits to a canonical form before performing amerge to reduce unnecessary conflicts. For more information,see section "Merging branches with differing checkin/checkoutattributes" in gitattributes[5].

  • merge.stat

  • Whether to print the diffstat between ORIG_HEAD and the merge resultat the end of the merge. True by default.

  • merge.tool

  • Controls which merge tool is used by git-mergetool[1].The list below shows the valid built-in values.Any other value is treated as a custom merge tool and requiresthat a corresponding mergetool..cmd variable is defined.

  • merge.guitool

  • Controls which merge tool is used by git-mergetool[1] when the-g/—gui flag is specified. The list below shows the valid built-in values.Any other value is treated as a custom merge tool and requires that acorresponding mergetool..cmd variable is defined.
  • araxis

  • bc

  • bc3

  • codecompare

  • deltawalker

  • diffmerge

  • diffuse

  • ecmerge

  • emerge

  • examdiff

  • guiffy

  • gvimdiff

  • gvimdiff2

  • gvimdiff3

  • kdiff3

  • meld

  • opendiff

  • p4merge

  • smerge

  • tkdiff

  • tortoisemerge

  • vimdiff

  • vimdiff2

  • vimdiff3

  • winmerge

  • xxdiff

  • merge.verbosity
  • Controls the amount of output shown by the recursive mergestrategy. Level 0 outputs nothing except a final errormessage if conflicts were detected. Level 1 outputs onlyconflicts, 2 outputs conflicts and file changes. Level 5 andabove outputs debugging information. The default is level 2.Can be overridden by the GIT_MERGE_VERBOSITY environment variable.

  • merge..name

  • Defines a human-readable name for a custom low-levelmerge driver. See gitattributes[5] for details.

  • merge..driver

  • Defines the command that implements a custom low-levelmerge driver. See gitattributes[5] for details.

  • merge..recursive

  • Names a low-level merge driver to be used whenperforming an internal merge between common ancestors.See gitattributes[5] for details.

  • branch..mergeOptions

  • Sets default options for merging into branch . The syntax andsupported options are the same as those of git merge, but optionvalues containing whitespace characters are currently not supported.

SEE ALSO

git-fmt-merge-msg[1], git-pull[1],gitattributes[5],git-reset[1],git-diff[1], git-ls-files[1],git-add[1], git-rm[1],git-mergetool[1]

GIT

Part of the git[1] suite