git switch command
git switchThe command is used for clearer branch switching.
git switchCommand function andgit checkoutSimilar, but provides clearer semantics and error checking.
Switch branch
The following command allows you to switch from the current branch to the specified branch.<branch-name>:
git switch <branch-name>
For example, to switch your working directory to the main branch:
git switch master
Create a new branch and switch
If you want to create a new branch and switch to it at the same time, you can use thegit switchAdd after the command-cor--createoption, then specify the branch name.
The following command is used to create a new branch.<new-branch-name>and immediately switch to the newly created branch:
git switch -c <new-branch-name>
For example, to create a new branch named feature-branch and switch to it:
git switch -c feature-branch
This will create a new branch named "feature-branch" and switch your working directory to that branch.
Switch to the previous branch
The following command allows you to quickly switch back to the previous branch without needing to remember the branch name:
git switch -
Restore the working directory to a specific commit state.
git switch <commit_hash>
This will switch the working directory to the state of the specified commit <commit_hash>, placing you in a detached HEAD state (i.e., no longer on any branch, but directly pointing to a specific commit).
In addition to these basic usages, git switch has some other options and usages, for example:
- Usage
-dor--detachThe option makes switching to a commit more explicit, and will not switch to a branch even if a branch with the same name exists. - Usage
-cThe option creates a new branch and immediately switches to it, similar togit switch -c <branch_name>Same. - Usage
-for--forceThe option can force the switch operation even if there are uncommitted changes.
View available branches and tags.
The following command allows you to list available local branches and tags, so you can quickly select a target to switch to:
git branch
Unlike git checkout, git switch is easier to understand and use because it focuses on branch switching operations. In addition, git switch provides better error checking, which can avoid some common mistakes.
Note:git switch is a new command introduced in Git 2.23. If you are using an older version of Git, the git switch command may not be available, but you can still usegit checkoutperform the same operation.
other extensions