Skip to main content
All posts

Basic Git Series: Creating and Switching Branches

A quick guide on how to create and switch Git branches

Overview

Branches allow you to work on different features or fixes simultaneously without affecting the main codebase. They're essential for collaborative development.

Steps

Creating a New Branch

  1. Ensure you're in the right starting point (usually main/master branch)
  2. Create a new branch and switch to it in one command:
git checkout -b new-branch-name

Switching Between Branches

git checkout branch-name

Listing All Branches

git branch

Creating Branches on GitHub

You can also create and switch branches directly on GitHub:

  1. Navigate to the repository on GitHub
  2. Click on the branch dropdown (shows the current branch, usually "main")
  3. Type a new branch name in the search box
  4. Click "Create branch: [name] from 'main'"

This creates the branch on GitHub, but you'll need to pull it to your local repository to work with it.

Common Issues

  • Cannot switch branches due to uncommitted changes: Commit or stash your changes before switching
  • Branch already exists: Use a different name or delete the existing branch
  • Missing remote branch: You may need to fetch the latest changes:

    git fetch origin
    git checkout branch-name

Additional Notes

  • Use descriptive branch names that reflect the feature or fix
  • Modern Git allows using git switch instead of git checkout for branch operations:

    git switch -c new-branch-name  # Create and switch
    git switch branch-name         # Just switch