Git 2.23 came up with the new ‘ git switch ’ command, which is not a new feature but an additional command to ‘switch/change branch’ feature which is already available in the overloaded git checkout command.
Currently, the all-encompassing command – git checkout does many things. It can be used to switch branches and also to restore the working tree files.
To separate out the functionalities, the GIT community introduced the new git switch branch command which is an attempt to start to scale back to the responsibilities without breaking backward compatibility.
git switch <branch>
Before going directly to the examples, let’s show all the branches that exist in the repo.
Let’s suppose there is an existing branch called develop and we want to switch from master to develop branch. To do that execute:
git switch develop
To switch branch to master
git switch master
Let’s try once more. Suppose there is another branch called feature and we want to switch to it.
git switch feature
This time to switch back to master, we can use another shorthand that switches to the previous branch before we switched.
git switch -
Let’s suppose we want to create a new branch which doesn’t exist and also at the same time we want to switch to it. For that
git switch -c new-branch
git branch new-branch
git switch new-branch
To switch to a remote branch,
git switch -c <branch> --track <remote>/<branch>
Note:- Execute a git fetch command before, to fetch the latest remote updates (including the remote branches).
So what has changed? What’s the difference between checkout and switch commands? Nothing special. git switch has almost copied and separated out the switching functionality from the git checkout command.
The new commands, git restore (takes care of operations that change file), and the git switch (takes care of operations that change branches) shares out the responsibilities of git checkout in a more intuitive way.
Have you started to use the new git switch command? Share and let your friends know.