git switch, git switch -c, git switch --detach
git switch <branch>
git switch -c <new-branch>
git switch --detach <commit>Move HEAD to a branch, create a branch and switch to it, or detach HEAD at a commit.
| Parameter | Description |
|---|---|
<branch> | An existing branch to check out. |
-c <new-branch> | Create the branch at HEAD, or at a given start point, and switch to it. |
--detach [<commit>] | Point HEAD at a commit instead of a branch. The default is HEAD itself. |
Returns: HEAD, the index, and the working tree match the chosen branch or commit, unless the switch is rejected.
- Switch progress messages go to standard error on Git 2.39.5. The example merges them into the output with 2>&1.
git init -b main >/dev/null
git config user.name "Practice Author"
git config user.email "[email protected]"
git config commit.gpgsign false
git config color.ui false
mkdir -p .disabled-hooks
git config core.hooksPath ".disabled-hooks"
printf 'base\n' > file.txt
git add file.txt
git commit -m "Add file" >/dev/null
echo "create"
git switch -c topic 2>&1
echo "current=$(git branch --show-current)"
echo "switch-main"
git switch main 2>&1
echo "current=$(git branch --show-current)"
echo "file=$(cat file.txt)"
echo "detach"
git switch --detach HEAD 2>&1
echo "detach-exit=$?"
echo "show-current=$(git branch --show-current)"
echo "abbrev=$(git rev-parse --abbrev-ref HEAD)"
git status --porcelain -b
echo "reattach"
git switch main 2>&1
echo "current=$(git branch --show-current)"
Expected output
create
Switched to a new branch 'topic'
current=topic
switch-main
Switched to branch 'main'
current=main
file=base
detach
HEAD is now at 8bb07df Add file
detach-exit=0
show-current=
abbrev=HEAD
## HEAD (no branch)
reattach
Switched to branch 'main'
current=main
Related: git branch, git status