Git by Example: Branch Creation
Learn how to create new branches in Git to isolate your work. This example covers creating branches with git branch and the modern git switch command.
Code
# Create a new branch named "feature-login"
git branch feature-login
# Verify the branch was created
git branch
# Output:
# feature-login
# * main
# Create and switch to a new branch in one step (old way)
git checkout -b feature-signup
# Create and switch to a new branch in one step (new way)
git switch -c feature-dashboard
# Output:
# Switched to a new branch 'feature-dashboard'Explanation
Branches are the core of Git's workflow, allowing you to diverge from the main line of development and work on new features or fixes in isolation. A branch in Git is simply a lightweight movable pointer to a commit. Creating a branch is instantaneous, regardless of the size of your project.
The git branch command creates a new branch pointer but does not switch you to it. To start working on the new branch, you must explicitly switch to it. Historically, git checkout -b was the standard command to create and switch in one go.
In modern Git (version 2.23+), the git switch command was introduced to separate branch switching responsibilities from the overloaded git checkout command. Using git switch -c (create) is now the recommended way to start a new branch and switch to it immediately.
- Branches are lightweight pointers to commits
- Use
git branchto list or create branches - Use
git switch -cto create and switch simultaneously - Keeps your main branch clean and stable
Code Breakdown
git checkout -b is the classic command to create a branch and switch to it immediately. You will see this in many older tutorials and scripts.git switch -c is the modern equivalent. It is more intuitive: "switch" to a new branch that you "create" (-c).
