Git – Create a Branch From Another Branch

Branching in Git allows developers to work on isolated features or fixes without affecting the main codebase. However, what if you need to create a new branch based on the changes in another branch? That’s where the concept of branching from another branch comes into play. In this guide, we’ll see the process of creating a branch from another branch in Git.

Table of Content

  • What is Git?
  • Branching in Git
  • Why Create a Branch from Another Branch?
  • Steps to Create a Branch From Another Branch

What is Git?

Git is distributed version control system used for tracking changes in source code during software development.

  • Git is designed to handle everything from small to very large projects with speed and efficiency.
  • It allows multiple developers to work on the same codebase concurrently.
  • Git stores data in a series of snapshots, which represent the state of the code at a specific point in time.

Branching in Git

Before creating branches from other branches, let’s quickly recap the basics of Git branching:

  • Master Branch: The master branch typically represents the main codebase, stable and production-ready.
  • Feature Branches: Developers create feature branches to work on specific features or fixes. These branches are typically created from the master branch.
  • Merge and Rebase: Once work on a feature branch is complete, changes are merged back into the master branch using either merge or rebase strategies.

Why Create a Branch from Another Branch?

While the master branch serves as the primary branch for stable code, there are scenarios where creating a branch from another branch becomes necessary:

  1. Parallel Development: When multiple developers are working on related features, they might create feature branches from a common development branch rather than directly from the master branch.
  2. Code Isolation: Sometimes, you need to isolate changes in a separate branch to test or experiment with them before merging into the main codebase.

Steps to Create a Branch From Another Branch

Step 1: Ensure that you have checked out the branch from which you want to create the new branch. You can use the git checkout command to switch to the branch.

git checkout existing-branch

Step 2: Use the git branch command to create a new branch.

git branch new-branch

Step 3: Switch to the new branch using the git checkout command.

git checkout new-branch

Step 4: Make changes to the new branch as needed. You can commit your changes to the new branch using the git commit command.

git commit -m "Commit message"

Step 5: If you want to push the new branch to a remote repository, use the git push command.

git push -u origin new-branch

Example

Step 1: Open Git Bash.

 

Step 2: Navigate to Git Directory.

Git Directory

Step 3: Create a Branch and Switch to it.

Creating a branch

Step 4: View Branch List.

List of Branch

Step 5: Switch Branch

Switch the branch


Contact Us