Git & GitHub - Merging Branches
How to merge branches in Git
Merging branches is an essential part of Git workflow, allowing you to integrate changes from different branches into a single branch. This guide explains how to merge branches in Git, including resolving conflicts that may arise during the merge process.
Key Points:
- Merging integrates changes from one branch into another.
- Conflicts can occur when changes in the branches overlap, requiring manual resolution.
- Git provides several commands and options to help manage and resolve merges.
Preparing for a Merge
Before merging branches, ensure that your working directory is clean and all changes are committed. This prevents any uncommitted changes from causing conflicts.
# Check the status of your repository
$ git status
# Commit any pending changes
$ git add .
$ git commit -m "Commit message"
Merging a Branch
To merge a branch into your current branch, use the git merge
command followed by the name of the branch you want to merge. Ensure you are on the branch into which you want to merge changes.
# Switch to the main branch
$ git checkout main
# Merge the feature branch into the main branch
$ git merge feature-branch
This command integrates the changes from feature-branch
into main
.
Resolving Merge Conflicts
Merge conflicts occur when changes in the branches being merged overlap. Git marks the conflicted areas in the files, and you need to resolve these conflicts manually.
# Example of a merge conflict marker
<<<<<<< HEAD
This is the main branch content.
=======
This is the feature branch content.
>>>>>>> feature-branch
- Edit the conflicted file to resolve the conflict.
- Remove the conflict markers and keep the desired changes.
- Stage the resolved file using
git add
. - Complete the merge by committing the changes.
# Stage the resolved file
$ git add conflicted-file.txt
# Commit the merge
$ git commit -m "Resolve merge conflict"
Viewing Merge History
To view the history of merges in your repository, use the git log
command with the --merges
option. This displays a log of all merge commits.
# View merge history
$ git log --merges
Using Merge Tools
Git supports external merge tools to help resolve conflicts. You can configure and use these tools to provide a more visual and interactive way of handling merge conflicts.
# Configure a merge tool (example with Meld)
$ git config --global merge.tool meld
# Use the merge tool to resolve conflicts
$ git mergetool
Summary
This guide covered the basics of merging branches in Git, including preparing for a merge, performing the merge, resolving conflicts, and using merge tools. Merging is a crucial part of the Git workflow that helps integrate changes from different branches, enabling collaborative development and efficient project management.