← Back to Chapters

Git Merge

? Git Merge

? Quick Overview

Git Merge is a core Git operation used to combine changes from different branches into one. It is commonly used when a feature branch is complete and needs to be integrated into the main branch.

? Key Concepts

  • Combines branch histories
  • Creates merge commits
  • Can cause merge conflicts
  • Supports multiple strategies

? Syntax / Theory

Merging integrates the commit history of one branch into another, preserving development context and collaboration history.

? Code Examples

? View Code Example
// Switch to the main branch before merging
git checkout main
? View Code Example
// Merge a feature branch into main
git merge feature-xyz

? Merge Conflicts

? View Code Example
// Git conflict markers inside a file
<<<<<<< HEAD
Changes from current branch
=======
Changes from feature branch
>>>>>>> feature-xyz

? Live Output / Explanation

After resolving conflicts and committing, Git records a merge commit with two parent commits, preserving both histories.

? Interactive Explanation

Think of Git merge like combining two timelines into one, ensuring every important change is included without losing history.

? Merge Strategies

? View Code Example
// Use the 'ours' merge strategy
git merge -s ours feature-xyz

⚡ Fast-Forward Merge

? View Code Example
// Force a merge commit even when fast-forward is possible
git merge --no-ff feature-xyz

? Use Cases

  • Integrating completed features
  • Combining hotfixes
  • Collaborative development

? Tips & Best Practices

  • Always pull latest changes before merging
  • Use --no-ff to preserve history
  • Test thoroughly after conflict resolution

? Try It Yourself

  • Create two branches
  • Modify the same file differently
  • Merge and resolve conflicts
  • Inspect merge commit using git log