Switching branches in Git is a common task and can be done easily using the Git command line. Here's a step-by-step guide:

Open your terminal: You can use Git Bash, Command Prompt, or any terminal that supports Git commands.

Navigate to your project directory: Use the cd command to change the directory to your project folder. For example:

cd path/to/your/project

Check the available branches: You can list all branches in your repository by using:

git branch

This will show you all branches and indicate the current branch with an asterisk (*).

Switch to the desired branch: Use the git checkout command followed by the branch name to switch to that branch. For example, to switch to a branch named feature-branch:

git checkout feature-branch

Confirm the switch: You can confirm that you've switched branches by running:

git branch

Again, this will list all branches, with an asterisk (*) next to the branch you are currently on.

Alternatively, if you are using a more recent version of Git (2.23 and above), you can use the git switch command, which is more intuitive for switching branches:

git switch feature-branch

Example:

cd my-project
git branch
# Output:
# * main
#   feature-branch

git checkout feature-branch
# Switched to branch 'feature-branch'

git branch
# Output:
#   main
# * feature-branch

Notes:

  • If the branch you want to switch to does not exist locally but exists on the remote repository, you can create and switch to the new branch by using:
git checkout -b feature-branch origin/feature-branch
  • If you have uncommitted changes in your current branch, Git might prevent you from switching branches to avoid losing those changes. In this case, you can either commit your changes, stash them using git stash, or discard them.

These steps should help you smoothly switch between branches in your Git repository.

Simon

102 Articles

I love talking about tech.