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
- Ensure you're in the right starting point (usually main/master branch)
- Create a new branch and switch to it in one command:
git checkout -b new-branch-nameSwitching Between Branches
git checkout branch-nameListing All Branches
git branchCreating Branches on GitHub
You can also create and switch branches directly on GitHub:
- Navigate to the repository on GitHub
- Click on the branch dropdown (shows the current branch, usually "main")
- Type a new branch name in the search box
- 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 switchinstead ofgit checkoutfor branch operations:git switch -c new-branch-name # Create and switch git switch branch-name # Just switch