git switch command
git switch The command is used to switch branches more clearly.
git switch The function of the command is similar to git checkout , but it provides clearer semantics and error checking.
Switch branches
The following command allows you to switch from the current branch to the specified branch
git switch
For example, to switch your working directory to the main branch:
git switch master
Create a new branch and switch to it
If you want to create a new branch and switch to it at the same time, you can add the -c or --create option after the git switch command, then specify the branch name.
The following command is used to create a new branch
git switch -c
For example, create a new branch named feature-branch and switch to it:
git switch -c feature-branch
This creates a new branch named "feature-branch" and switches your working directory to that branch.
Switch to the previous branch
The following command lets you quickly switch back to the previous branch without having to remember the branch name:
git switch -
Restore the working directory to a specific commit state
git switch
This switches the working directory to the state of the specified commit
In addition to these basic uses, git switch has other options and usages, for example:
- Use
-dor--detachoption can make the operation of switching to a commit more explicit; even if a branch with the same name exists, it will not switch to the branch. - Use
-coption creates a new branch and immediately switches to it, similar togit switch -c. - Use
-for--forceoption can force the switch operation even if there are uncommitted changes.
View available branches and tags
The following commands let you list available local branches and tags to quickly choose the 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 that can avoid some common erroneous operations.
**Note:** git switch is a new command introduced in Git 2.23. If you are using an older version of Git, you may not be able to use the git switch command, but you can still use git checkout to perform the same operation.
Git Basic Operations