Q10 of 40 · Git

How do you create a new branch and switch to it?

GitJuniorgitbranchingswitchcreate-branchfundamentals

Short answer

Short answer: git switch -c feature/my-branch creates and switches in one command (modern syntax). To base it on a specific point: git switch -c feature/name origin/main. The older equivalent is git checkout -b. After creating, git push -u origin feature/my-branch sets the upstream and enables plain git push for subsequent pushes.

Detail

Modern commands (Git 2.23+):

  • git switch -c <name> — create and switch (c = create)
  • git switch <existing-branch> — switch to existing branch
  • git switch - — switch to the previous branch (like cd -)

Older equivalent (still widely used):

  • git checkout -b <name> — create and switch
  • git checkout <name> — switch to existing

Branch naming conventions (common in test repos):

  • feature/add-login-tests
  • fix/flaky-payment-test
  • chore/upgrade-rest-assured-5.x
  • test/add-edge-cases-for-checkout

Basing on a specific start point is important in test repos — you usually want your test branch to start from the latest main, not from an old commit:

git fetch origin                    # get latest remote state
git switch -c feature/new-tests origin/main  # start from latest main

// EXAMPLE

# Create a new branch from current HEAD and switch to it
git switch -c feature/checkout-api-tests

# Create from a specific remote branch (recommended — ensures you're up to date)
git fetch origin
git switch -c feature/checkout-api-tests origin/main

# Set upstream so plain 'git push' and 'git pull' work
git push -u origin feature/checkout-api-tests

# Older equivalent (still valid)
git checkout -b feature/checkout-api-tests origin/main

# Jump back to the previous branch
git switch -

# List all branches with last commit info
git branch -vv

// WHAT INTERVIEWERS LOOK FOR

Using git switch -c (modern) over git checkout -b, fetching before creating a branch to start from the latest remote state, and setting the upstream with -u on first push. These are the habits of engineers who have worked in team environments.

// COMMON PITFALL

Creating a branch from a stale local main instead of from origin/main — the branch starts from an old commit and immediately diverges in ways that cause confusing conflicts when rebasing later.