How to Merge a Branch into Main in Git: Simple Steps
To merge a branch into
main, first switch to the main branch using git checkout main or git switch main, then run git merge branch-name to combine the changes. This updates main with the commits from the other branch.Syntax
The basic syntax to merge a branch into main involves two steps:
- Switch to main branch:
git checkout mainorgit switch main - Merge the branch:
git merge branch-name
This tells Git to apply the changes from branch-name into main.
bash
git checkout main git merge branch-name
Example
This example shows merging a branch called feature into main. It demonstrates switching branches and merging changes.
bash
git checkout main # Output: Switched to branch 'main' git merge feature # Output: Updating abc1234..def5678 # Fast-forward # file.txt | 2 ++ # 1 file changed, 2 insertions(+)
Output
Switched to branch 'main'
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
mainfirst, which merges into the wrong branch. - Not committing or stashing local changes before merging, causing conflicts.
- Ignoring merge conflicts that need manual resolution.
Always ensure you are on main and your working directory is clean before merging.
bash
git merge feature
# Wrong if not on main branch
# Correct way:
git checkout main
git merge featureQuick Reference
Here is a quick cheat sheet for merging a branch into main:
| Command | Description |
|---|---|
| git checkout main | Switch to the main branch |
| git switch main | Alternative to checkout for switching branches |
| git merge branch-name | Merge the specified branch into main |
| git status | Check for uncommitted changes before merging |
| git log --oneline --graph | View commit history and merge status |
Key Takeaways
Always switch to the main branch before merging another branch into it.
Use 'git merge branch-name' to combine changes from the branch into main.
Ensure your working directory is clean to avoid merge conflicts.
Resolve any merge conflicts manually if they occur.
Use 'git status' and 'git log' to verify your branch state before and after merging.