How to create a new Git branch and switch to it
· Category: Git
Short answer
Use git checkout -b new-branch-name to create and switch to a new branch in one command. Alternatively, use git branch new-name followed by git checkout new-name. For resolving conflicts when merging branches, see how to resolve Git merge conflicts. For moving specific commits between branches, see how to cherry-pick a commit in Git.
Steps
- Ensure you are on the correct base branch:
git checkout main - Pull latest changes:
git pull origin main - Create and switch:
git checkout -b feature/user-login - Make your changes and commit
- Push the branch:
git push -u origin feature/user-login
Tips
- Use descriptive branch names:
feature/,bugfix/,hotfix/prefixes - If you need to fix a commit after creating the branch, see how to amend a Git commit
- To share your branch with others, first add a remote repository