Branching

Git Merge

Merging Branches

Git merge combines branches resolving conflicts manually.

Understanding Git Merge

Git merge is a powerful feature in Git that allows you to combine two or more branches into a single branch. This operation is commonly used to integrate changes from different branches, ensuring that all updates are consolidated into a mainline branch or a feature branch.

Basic Git Merge Usage

To merge a branch into the current branch, you can use the following command:

Replace <branch-name> with the name of the branch you want to merge into your current branch. For example, if you are on the main branch and want to merge a branch called feature, you would run:

Resolving Merge Conflicts

Merge conflicts occur when changes in different branches conflict with each other. Git will pause the merging process and allow you to resolve the conflicts manually. Here's how you can handle merge conflicts:

  • Open the files with conflicts in your text editor.
  • Look for conflict markers like <<<<<<< HEAD and =======.
  • Decide which changes to keep or how to merge the changes.
  • Remove the conflict markers.
  • Save the file and add it to the staging area with git add <file-name>.

Finalizing the Merge

After resolving conflicts, you need to complete the merge by committing the changes. Use the following command:

This will commit the merge changes, and your branches will be successfully merged.

Fast-Forward Merge

A fast-forward merge occurs when the current branch is directly ahead of the branch being merged. In this case, Git simply moves the current branch pointer forward without creating an additional merge commit. This can be enabled with:

If no conflicts are present and a fast-forward merge is possible, this is the default behavior.

No Fast-Forward Merge

If you want to prevent Git from performing a fast-forward merge, which is useful for maintaining a history of merges, you can use the --no-ff option:

This will create an explicit merge commit, even if no conflicts are present, preserving the branch history.

Previous
Checkout