0
0
GitHow-ToBeginner · 3 min read

How to Merge Main into Feature Branch in Git

To merge main into your feature branch, first switch to your feature branch using git checkout feature-branch. Then run git merge main to bring the latest changes from main into your feature branch.
📐

Syntax

The basic syntax to merge the main branch into your feature branch involves two steps:

  • Switch to your feature branch: git checkout feature-branch
  • Merge main into it: git merge main

This updates your feature branch with the latest commits from main.

bash
git checkout feature-branch
git merge main
💻

Example

This example shows how to update a feature branch named feature-login with the latest changes from main. It assumes you have a local copy of both branches.

bash
git checkout feature-login
Switched to branch 'feature-login'
git merge main
Updating 1a2b3c4..5d6e7f8
Fast-forward
 src/login.js | 10 ++++++++++
 1 file changed, 10 insertions(+)
Output
Switched to branch 'feature-login' Updating 1a2b3c4..5d6e7f8 Fast-forward src/login.js | 10 ++++++++++ 1 file changed, 10 insertions(+)
⚠️

Common Pitfalls

Common mistakes when merging main into a feature branch include:

  • Not switching to the feature branch before merging, which merges main into the wrong branch.
  • Having uncommitted changes in the feature branch, causing merge conflicts or errors.
  • Ignoring merge conflicts that require manual resolution.

Always commit or stash your changes before merging and carefully resolve conflicts if they appear.

bash
git merge main
# Error: You have uncommitted changes

# Correct approach:
git stash
# Save changes temporarily

git merge main
# Merge main

git stash pop
# Restore your changes
📊

Quick Reference

Here is a quick cheat sheet for merging main into your feature branch:

CommandDescription
git checkout feature-branchSwitch to your feature branch
git merge mainMerge latest changes from main into feature branch
git stashTemporarily save uncommitted changes
git stash popRestore saved changes after merge
git statusCheck branch status and conflicts

Key Takeaways

Always switch to your feature branch before merging main.
Commit or stash your changes to avoid merge errors.
Use git merge main to bring main branch updates into your feature branch.
Resolve any merge conflicts carefully before continuing.
Check your branch status with git status after merging.