How to Create a Git Branch from Another Branch Easily
To create a new branch from another branch in Git, first switch to the source branch using
git checkout source-branch, then create and switch to the new branch with git checkout -b new-branch. This makes the new branch start from the current state of the source branch.Syntax
The process involves two main commands:
git checkout source-branch: Switches your working directory to the branch you want to base your new branch on.git checkout -b new-branch: Creates a new branch namednew-branchstarting from the current branch and switches to it immediately.
bash
git checkout source-branch
git checkout -b new-branchExample
This example shows how to create a branch named feature from an existing branch called develop. It first switches to develop, then creates and switches to feature.
bash
$ git checkout develop Switched to branch 'develop' $ git checkout -b feature Switched to a new branch 'feature'
Output
Switched to branch 'develop'
Switched to a new branch 'feature'
Common Pitfalls
One common mistake is creating a new branch without switching to the source branch first, which causes the new branch to start from the current branch instead of the intended one.
Wrong way:
git checkout -b new-branch source-branch
This command works and switches to the new branch starting from source-branch, but it does not switch to source-branch first, which can confuse beginners about the current branch context.
Right way:
git checkout source-branch git checkout -b new-branch
This ensures you are on the correct base branch before creating the new one.
bash
git checkout -b new-branch source-branch # This creates new-branch from source-branch and switches to it immediately # Recommended approach: git checkout source-branch git checkout -b new-branch
Quick Reference
| Command | Description |
|---|---|
| git checkout source-branch | Switch to the branch you want to base your new branch on |
| git checkout -b new-branch | Create and switch to a new branch from the current branch |
| git branch new-branch source-branch | Create a new branch from source-branch without switching to it |
| git switch -c new-branch source-branch | Create and switch to a new branch from source-branch (modern alternative) |
Key Takeaways
Always switch to the source branch before creating a new branch to ensure correct starting point.
Use
git checkout -b new-branch to create and switch to the new branch in one step.You can create a branch from another branch without switching using
git branch new-branch source-branch.The modern alternative to
git checkout is git switch -c new-branch source-branch.Check your current branch with
git status to avoid confusion before creating branches.