After working independently on different branches, the common goal is usually to integrate these separate lines of development back into a main branch, like main
or master
. This process of combining the history and changes from different branches is called merging. Git provides the git merge
command specifically for this purpose.
Merging takes the changes from a source branch (e.g., your feature branch) and integrates them with the history of a target branch (e.g., the main
branch). Git is remarkably good at figuring out how to combine these changes automatically.
git merge
CommandTo perform a merge, you first need to switch to the branch that you want to merge into. This is typically your main line of development, such as the main
branch. Once you are on the target branch, you use the git merge
command, specifying the name of the branch you want to merge from.
For example, if you have finished work on a branch named new-feature
and want to integrate those changes into your main
branch, you would run the following commands:
Switch to the target branch (main
):
git switch main
Or, using the older command:
git checkout main
Merge the source branch (new-feature
) into the current branch (main
):
git merge new-feature
When you execute git merge
, Git performs several steps behind the scenes:
If the changes occurred in different parts of the files or in different files altogether, Git can often combine them automatically without any issues.
Often, when changes have occurred on both branches since they diverged, Git will create a new, special commit called a merge commit. This commit acts as a unification point in the project history. Its defining characteristic is that it has more than one parent commit: one pointing to the tip of the branch you were on (e.g., main
), and another pointing to the tip of the branch you merged in (e.g., new-feature
).
This merge commit doesn't introduce new file changes itself (unless conflicts needed resolving), but rather serves as a record that the histories of the two branches were combined at this point.
A merge commit (M) combines work from two parent commits (B on the
main
branch, D on thenew-feature
branch), integrating the divergent histories. Themain
label now points to M.
After running git merge new-feature
while on main
, Git might output messages indicating the files that were changed and confirming the creation of the merge commit (if one was necessary). Your main
branch now incorporates all the work done on the new-feature
branch.
Merging is a fundamental operation for integrating work in Git. While it often works smoothly, sometimes Git encounters situations where changes on the merging branches conflict with each other. We will discuss how Git handles simpler merge scenarios (fast-forward merges) and how to resolve conflicts in the following sections.
© 2025 ApX Machine Learning