How to Merge Branch in Git: Simple Guide with Examples
To merge a branch in Git, first switch to the branch you want to merge into using
git checkout, then run git merge <branch-name> to combine changes from the other branch. This integrates the changes into your current branch.Syntax
The basic syntax to merge a branch in Git is:
git checkout <target-branch>: Switch to the branch where you want to add changes.git merge <source-branch>: Merge the source branch into the current branch.
bash
git checkout main git merge feature-branch
Example
This example shows how to merge a branch named feature-branch into main. First, switch to main, then merge the changes from feature-branch.
bash
git checkout main git merge feature-branch
Output
Updating abc1234..def5678
Fast-forward
file.txt | 2 ++
1 file changed, 2 insertions(+)
Common Pitfalls
Common mistakes when merging branches include:
- Trying to merge without switching to the target branch first.
- Not committing changes before merging, which can cause conflicts.
- Ignoring merge conflicts instead of resolving them properly.
Always commit or stash your changes before merging to avoid losing work.
bash
git merge feature-branch # Error: You are not currently on a branch. # Correct way: git checkout main git merge feature-branch
Quick Reference
| Command | Description |
|---|---|
| git checkout | Switch to the branch where you want to merge changes |
| git merge | Merge the specified branch into the current branch |
| git status | Check current branch and uncommitted changes |
| git log --oneline --graph | View commit history and branch merges |
Key Takeaways
Always switch to the target branch before merging with
git checkout.Use
git merge <branch> to combine changes from another branch.Commit or stash your changes before merging to avoid conflicts.
Resolve merge conflicts carefully if they occur.
Use
git status and git log to understand your branch state.