Branching and Merging in Git

Difficulty: intermediate
Est. Time: 40 minutes
Prerequisites:
  • Initializing a Repository and Making Your First Commit
Branching and Merging in Git
12 min
TUTORIAL
git
branching
merging
intermediate

Branching and Merging in Git

Branching is one of Git’s most powerful features. It allows you to work on different versions of your project simultaneously. In this blog, we’ll explore how to create, switch, and merge branches.

Table of Contents

  • Branch
  • Merge
  • Creating and Switching Branches
  • Merging Branches
  • Exercise: Practicing Branching and Merging

Branch

A branch is a parallel line of development. The default branch is usually main or master.

Merge

Merging combines changes from one branch into another.

Creating and Switching Branches

  1. Create a new branch:
  2. 
      git branch feature-branch
                
  3. Switch to the new branch:
  4. 
      git checkout feature-branch
                
  5. Or use the shortcut:
  6. 
      git switch feature-branch
                

Merging Branches

  1. Make changes in the feature-branch and commit them.
  2. Switch back to main:
  3. 
      git checkout main
                
  4. Merge the branches:
  5. 
      git merge feature-branch
                

Git Graph After Merging


        Commit B (feature-branch)
       /
  Commit A ---- Commit C (merge commit)
          

Exercise

Create a new branch called experiment. Make changes in the experiment branch and commit them. Switch back to main and merge the experiment branch. Run git log --graph to visualize the branch structure.

Coming Up Next

In the next part of this series, we’ll tackle resolving merge conflicts when Git cannot automatically merge changes.

Part 3 of 24 in Git Mastery Series: From Beginner to Expert
All Posts in This Series