There are several ways to switch branches in Git:
git checkout
: This command is used to switch between branches in Git. For example, to switch from the current branch to the “feature-branch” branch, you would run the following command:
git checkout feature-branch
git switch
: This command is similar togit checkout
, but it is a newer command introduced in Git 2.23. To switch to a different branch usinggit switch
, you would run the following command:
git switch feature-branch
git branch
: This command is used to list, create, or delete branches in Git. To switch to an existing branch usinggit branch
, you first need to list all the branches using the following command:This will display a list of all the branches in your repository. To switch to a different branch, you would run the following command:
git branch //displays all branches git checkout <branch-name> // switch to the displayed branch git checkout -b <new-branch-name> // switches to new-branch if exists, otherwise it creates new-branch-name
git stash
: If you have uncommitted changes in your working directory that you want to save before switching branches, you can usegit stash
to temporarily save those changes. To stash your changes and switch to a different branch, run the following commands:
git stash git checkout git stash apply
- This will save your changes to the stash, switch to the new branch, and then apply the changes from the stash to the new branch.
In summary, git checkout
, git switch
, git branch
, and git stash
are all different approaches to switch between branches in Git, and you can choose the approach that works best for your workflow.