How do you create and switch between branches in Git?
Quick Answer
Use git branch <name> to create a branch and git checkout <name> or git switch <name> to switch to it. The shortcut git checkout -b <name> or git switch -c <name> creates and switches in one step.
Detailed Answer
Think of branches like parallel timelines in a sci-fi movie. The main timeline (main branch) keeps running, and you create a branch to explore an alternate timeline where you add a new feature. If that timeline works out, you merge it back into the main timeline. If not, you simply abandon it with no impact on the original story.
A branch in Git is simply a lightweight, movable pointer to a specific commit. When you create a branch with git branch feature/order-history, Git creates a new file in .git/refs/heads/ containing the SHA-1 hash of the current commit. No files are copied, no directories duplicated. This makes branch creation nearly instantaneous regardless of repository size. The HEAD pointer is a special reference that tells Git which branch you're currently on. When you switch branches with git checkout or the newer git switch command, Git updates HEAD to point to the new branch and updates your working directory to match that branch's latest commit.
Internally, when you switch branches, Git performs a three-way comparison between the current HEAD, the target branch, and the index. It updates files in the working directory that differ between the two branches. If you have uncommitted changes that would conflict with the target branch, Git will refuse the switch and warn you. This safety mechanism prevents accidental data loss. The checkout command has been split into two more focused commands in modern Git: git switch for changing branches and git restore for restoring files, because git checkout was overloaded with too many responsibilities.
In production team workflows, branch naming conventions are essential. Common patterns include feature/ticket-123-add-search, bugfix/null-pointer-in-cart, hotfix/security-patch-cve-2024, and release/v2.3.0. Many teams enforce these conventions through Git hooks or branch protection rules in GitHub or GitLab. The branching strategy directly impacts how CI/CD pipelines are configured. For example, pushes to feature/* branches might trigger unit tests only, while pushes to release/* branches trigger full integration and deployment pipelines.
A common gotcha: running git branch without arguments only lists local branches. Use git branch -r to see remote-tracking branches or git branch -a for all branches. Another frequent mistake is forgetting to switch to the new branch after creating it with git branch. You'll keep committing on the old branch. Always verify with git status which branch you're on. Also, trying to delete a branch you're currently on will fail. Switch to another branch first, then delete with git branch -d.