Script Valley
Git and GitHub Complete Course: From Beginner to Advanced
Branching, Merging, and Resolving ConflictsLesson 2.2

Creating and Switching Branches

git branch, git checkout, git switch, create branch, delete branch, branch naming conventions

Creating and Switching Branches

Creating and switching branches are the most frequent Git operations in professional development. Git provides two commands for switching branches: the older git checkout and the newer git switch. Both work, but git switch is more explicit and safer.

Creating a Branch

To create a new branch without switching to it:

git branch feature/user-login

To create and immediately switch to it:

git switch -c feature/user-login
# or the older syntax:
git checkout -b feature/user-login

Switching Between Branches

To switch to an existing branch:

git switch main
# or:
git checkout main

Before switching, ensure your working directory is clean. Either commit your changes or stash them with git stash.

Branch Naming Conventions

Consistent naming makes large repositories manageable. Common patterns include: feature/feature-name for new features, fix/bug-description for bug fixes, docs/section-name for documentation, and chore/task-name for maintenance tasks.

Deleting a Branch

After a feature branch is merged, delete it to keep the repository clean:

git branch -d feature/user-login

The -d flag only deletes a branch that has been fully merged. Use -D to force-delete an unmerged branch.

Up next

Merging Branches

Sign in to track progress

Creating and Switching Branches โ€” Branching, Merging, and Resolving Conflicts โ€” Git and GitHub Complete Course: From Beginner to Advanced โ€” Script Valley โ€” Script Valley