Browse topics

git switch

Version
2.51
Since
2.23
Review
Draft

Summary#

git switch changes the checked-out branch. Add -c with a new branch name to create it and switch in one operation.

Syntax#

sh
git switch branch
git switch -c new-branch

Example#

sh
(
  set -eu
  scratch=$(mktemp -d "${TMPDIR:-/tmp}/devlookup-git.XXXXXX")
  trap 'rm -rf -- "$scratch"' EXIT
  unset GIT_CONFIG_GLOBAL $(git rev-parse --local-env-vars)
  export GIT_CONFIG_NOSYSTEM=1 GIT_TEMPLATE_DIR= LC_ALL=C
  export HOME="$scratch" XDG_CONFIG_HOME="$scratch" GIT_ATTR_NOSYSTEM=1
  mkdir "$scratch/work"
  cd "$scratch/work"
  git init -q -b trunk
  git -c user.name="Reference Example" -c user.email=example@example.invalid commit --allow-empty -qm "Start"

  git switch -q -c topic/refine
  git branch --show-current
  git switch -q trunk
  git branch --show-current
)

Expected output#

Text
topic/refine
trunk

Common mistakes#

Git can refuse to switch if it would overwrite local edits. Commit or stash the relevant changes first. Use --detach to work directly from a commit. Create a branch before leaving detached HEAD if you want to keep any new commits.

Version applicability#

Git 2.23 added switch for branch operations. Older versions use git checkout branch or git checkout -b new-branch.

The complete example requires Git 2.28 or later for git init -b.

Sources#

Attribution
DevLookup contributors
License
CC-BY-4.0