Git Merge | Atlassian Git Tutorial (2024)

How it works

Git merge will combine multiple sequences of commits into one unified history.In the most frequent use cases, git merge is used to combine two branches. Thefollowing examples in this document will focus on this branch merging pattern.In these scenarios, git merge takes two commit pointers, usually the branchtips, and will find a common base commit between them. Once Git finds a commonbase commit it will create a new "merge commit" that combines the changes ofeach queued merge commit sequence.

Say we have a new branch feature that is based off the mainbranch. We nowwant to merge this feature branch into main.

Git Merge | Atlassian Git Tutorial (1)

Git Merge | Atlassian Git Tutorial (2)

related material

Advanced Git log

Read article

Invoking this command will merge the specified branch feature into the currentbranch, we'll assume main. Git will determine the merge algorithmautomatically (discussed below).

Git Merge | Atlassian Git Tutorial (4)

Merge commits are unique against other commits in the fact that they have twoparent commits. When creating a merge commit Git will attempt to auto magicallymerge the separate histories for you. If Git encounters a piece of data that ischanged in both histories it will be unable to automatically combine them. Thisscenario is a version control conflict and Git will need user intervention tocontinue.

Preparing to merge

Before performing a merge there are a couple of preparation steps to take toensure the merge goes smoothly.

Confirm the receiving branch

Execute git statusto ensure that HEAD is pointing to the correct merge-receiving branch. If needed, execute git checkout to switch to thereceiving branch. In our case we will execute git checkout main.

Fetch latest remote commits

Make sure the receiving branch and the merging branch are up-to-date with thelatest remote changes. Execute git fetch to pull the latest remote commits. Oncethe fetch is completed ensure the mainbranch has the latest updates byexecuting git pull.

Merging

Once the previously discussed "preparing to merge" steps have been taken a mergecan be initiated by executing git merge where is thename of the branch that will be merged into the receiving branch.

Fast forward merge

A fast-forward merge can occur when there is a linear path from the currentbranch tip to the target branch. Instead of “actually” merging the branches, allGit has to do to integrate the histories is move (i.e., “fast forward”) thecurrent branch tip up to the target branch tip. This effectively combines thehistories, since all of the commits reachable from the target branch are nowavailable through the current one. For example, a fast forward merge ofsome-feature into mainwould look something like the following:

Git Merge | Atlassian Git Tutorial (5)

However, a fast-forward merge is not possible if the branches have diverged.When there is not a linear path to the target branch, Git has no choice but tocombine them via a 3-way merge. 3-way merges use a dedicated commit to tietogether the two histories. The nomenclature comes from the fact that Git usesthree commits to generate the merge commit: the two branch tips and their commonancestor.

Git Merge | Atlassian Git Tutorial (6)

While you can use either of these merge strategies, many developers like to usefast-forward merges (facilitated through rebasing) for small features or bugfixes, while reserving 3-way merges for the integration of longer-runningfeatures. In the latter case, the resulting merge commit serves as a symbolicjoining of the two branches.

Our first example demonstrates a fast-forward merge. The code below creates anew branch, adds two commits to it, then integrates it into the main line with afast-forward merge.

#Startanewfeature
gitcheckout-bnew-featuremain
#Editsomefiles
gitadd<file>
gitcommit-m"Startafeature"
#Editsomefiles
gitadd<file>
gitcommit-m"Finishafeature"
#Mergeinthenew-featurebranch
gitcheckoutmain
gitmergenew-feature
gitbranch-dnew-feature

This is a common workflow for short-lived topic branches that are used more asan isolated development than an organizational tool for longer-running features.

Also note that Git should not complain about the git branch -d, sincenew-feature is now accessible from the mainbranch.

In the event that you require a merge commit during a fast forward merge forrecord keeping purposes you can execute git merge with the --no-ff option.

gitmerge--no-ff<branch>

This command merges the specified branch into the current branch, but alwaysgenerates a merge commit (even if it was a fast-forward merge). This is usefulfor documenting all merges that occur in your repository.

3-way merge

The next example is very similar, but requires a 3-way merge because mainprogresses while the feature is in-progress. This is a common scenario for largefeatures or when several developers are working on a project simultaneously.

Startanewfeature
gitcheckout-bnew-featuremain
#Editsomefiles
gitadd<file>
gitcommit-m"Startafeature"
#Editsomefiles
gitadd<file>
gitcommit-m"Finishafeature"
#Developthemainbranch
gitcheckoutmain
#Editsomefiles
gitadd<file>
gitcommit-m"Makesomesuper-stablechangestomain"
#Mergeinthenew-featurebranch
gitmergenew-feature
gitbranch-dnew-feature

Note that it’s impossible for Git to perform a fast-forward merge, as there isno way to move mainup to new-feature without backtracking.

For most workflows, new-feature would be a much larger feature that took a longtime to develop, which would be why new commits would appear on mainin themeantime. If your feature branch was actually as small as the one in the aboveexample, you would probably be better off rebasing it onto mainand doing afast-forward merge. This prevents superfluous merge commits from cluttering upthe project history.

Resolving conflict

If the two branches you're trying to merge both changed the same part of thesame file, Git won't be able to figure out which version to use. When such asituation occurs, it stops right before the merge commit so that you can resolvethe conflicts manually.

The great part of Git's merging process is that it uses the familiaredit/stage/commit workflow to resolve merge conflicts. When you encounter amerge conflict, running the git status command shows you which files need to beresolved. For example, if both branches modified the same section of hello.py,you would see something like the following:

Onbranchmain
Unmergedpaths:
(use"gitadd/rm..."asappropriatetomarkresolution)
bothmodified:hello.py

How conflicts are presented

When Git encounters a conflict during a merge, It will edit the content of theaffected files with visual indicators that mark both sides of the conflictedcontent. These visual markers are: <<<<<<<, =======, and >>>>>>>. It's helpful tosearch a project for these indicators during a merge to find where conflictsneed to be resolved.

hereissomecontentnotaffectedbytheconflict
<<<<<<<main
thisisconflictedtextfrommain
=======
thisisconflictedtextfromfeaturebranch
>>>>>>>featurebranch;

Generally the content before the ======= marker is the receiving branch and thepart after is the merging branch.

Once you've identified conflicting sections, you can go in and fix up the mergeto your liking. When you're ready to finish the merge, all you have to do is rungit add on the conflicted file(s) to tell Git they're resolved. Then, you run anormal git commit to generate the merge commit. It’s the exact same process ascommitting an ordinary snapshot, which means it’s easy for normal developers to manage their own merges.

Note that merge conflicts will only occur in the event of a 3-way merge. It’snot possible to have conflicting changes in a fast-forward merge.

Summary

This document is an overview of the git merge command. Merging is an essentialprocess when working with Git. We discussed the internal mechanics behind amerge and the differences between a fast forward merge and a three way, truemerge. Some key take-aways are:

1. Git merging combines sequences of commits into one unified history ofcommits.

2. There are two main ways Git will merge: Fast Forward and Three way

3. Git can automatically merge commits unless there are changes that conflictin both commit sequences.

This document integrated and referenced other Git commands like: git branch, git pull, and git fetch. Visit their corresponding stand-alone pages for more information.

Share this article

Next Topic
Merge conflicts
Git Merge | Atlassian Git Tutorial (2024)
Top Articles
Latest Posts
Article information

Author: Sen. Emmett Berge

Last Updated:

Views: 6114

Rating: 5 / 5 (60 voted)

Reviews: 83% of readers found this page helpful

Author information

Name: Sen. Emmett Berge

Birthday: 1993-06-17

Address: 787 Elvis Divide, Port Brice, OH 24507-6802

Phone: +9779049645255

Job: Senior Healthcare Specialist

Hobby: Cycling, Model building, Kitesurfing, Origami, Lapidary, Dance, Basketball

Introduction: My name is Sen. Emmett Berge, I am a funny, vast, charming, courageous, enthusiastic, jolly, famous person who loves writing and wants to share my knowledge and understanding with you.