Git Switch



The git switch command is used to switch the branches in Git. It is a more modern command than git checkout and was introduced in Git 2.23 to simplify the process of branch switching.

Syntax

git switch <branch-name>

<branch-name> is the name of the branch to which you need to switch.

Options

The git switch command has the following options:

-c or --create

  • Using the command git switch -c creates a new branch and immediately switches to it.

git switch -c new-branch

git switch -create new-branch

-C or --create --force

  • Using the command git switch -C creates a new branch and immediately switches to it, even if the branch already exists. It resets the branch and overwrites it.

git switch -C <branch-name>

-f or --force

  • It switches branches and discard uncommitted changes.

git switch -f <branch-name>

--detach

  • It switches to the given commit, but detaches the HEAD, which signifies that you are no longer on any branch.

  • This effectively means that you are working with a commit, without affecting any branch.

git switch --detach <commit-hash>

--guess

  • Using this option will let you provide a part of the branch name and Git in turn will guess the name and return the result, switching to that branch.

  • This option enabled by default, but can be turned off using the option --no-guess.

git switch --guess <branch-name-part>

--track

  • This option automatically sets the tracking up of a new branch from a remote branch.

  • This option is useful when you are checking out a branch that exists on a remote repository, and you need to set the local branch to track the remote branch.

git switch --track <remote-branch>

--no-track

  • When a branch is created from a remote-tracking branch, Git sets the tracking of the branch automatically.

  • In order to prevent the tracking of branch, --no-track option can be used.

git switch --no-track <branch-name>

--orphan

  • Creates a new branch with no history. Useful to create new branches with a clean slate.

git switch --orphan <new-branch-name>

--discard-changes

  • Similar to -f, it will also switch branches while discarding the changes that are uncommitted in the working directory.

  • It is useful when you want discard the changes and don't want to force the switch.

git switch --discard-changes <branch-name>

--merge

  • This option avoids losing changes in the working directory by trying to merge them.

git switch --merge <branch-name>

--progress and --no-progress

  • This option controls whether progress needs to be displayed while switching or not.

  • It is generally used in long operations that may show the progress, such as checking out large files.

git switch --progress <branch-name>

git switch --no-progress <branch-name>

You can manage switching of branch with more precision and clarity with git switch as compared to the older commands like git checkout.

Advertisements