Understanding Git Branching and Merging

Tutorial 3 of 5

1. Introduction

This tutorial aims to provide an in-depth understanding of branching and merging in Git. By the end of this tutorial, you'll know how to create branches, switch between them, and merge changes.

You will learn:
- The concept of branching and merging.
- How to create, switch, and delete branches.
- How to merge branches.

Prerequisites: Basic understanding of Git and its commands.

2. Step-by-Step Guide

2.1 Git Branching

A branch in Git is simply a lightweight movable pointer to one of these commits. The default branch name in Git is master. As you start making commits, you're given a master branch that points to the last commit you made. Every time you commit, the master branch pointer moves forward automatically.

Creating a Branch

You can create a new branch with the git branch command. Let's say we want to create a new branch called feature.

git branch feature

Switching Between Branches

To switch from one branch to another, you can use the git checkout command. If you want to switch to the feature branch, you would use:

git checkout feature

2.2 Git Merging

Merging is Git's way of putting a forked history back together again. The git merge command lets you take the independent lines of development created by git branch and integrate them into a single branch.

git merge feature

This command merges the feature branch into the current branch.

3. Code Examples

3.1 Creating, Switching, and Deleting Branches

# Create a new branch named "feature"
git branch feature

# Switch to the "feature" branch
git checkout feature

# Return to the "master" branch
git checkout master

# Delete the "feature" branch
git branch -d feature

The -d option will delete the specified branch.

3.2 Merging Branches

# Create a new branch named "feature"
git branch feature

# Switch to the "feature" branch
git checkout feature

# Make some changes and commit them
git commit -m "Add new feature"

# Switch back to the "master" branch
git checkout master

# Merge the "feature" branch into the "master" branch
git merge feature

4. Summary

In this tutorial, we've learned about Git branching and merging. We learned to create, switch, and delete branches. We also learned how to merge changes from one branch into another.

Next, try to create more complex branches and experiment with merging.

For further reading, check out the official Git documentation.

5. Practice Exercises

  1. Exercise: Create a new branch called experiment, switch to it, make some changes, and then switch back to the master branch.

Solution:

git branch experiment
git checkout experiment
# make some changes
git checkout master
  1. Exercise: Merge the changes from the experiment branch into the master branch.

Solution:

git merge experiment
  1. Exercise: Delete the experiment branch.

Solution:

git branch -d experiment

Remember, practice is the key to mastering any skill, so keep practicing and experimenting.