Introduction
Git is an open-source application for tracking projects. Multiple users can work on the same project simultaneously. A project can be branched to evaluate features without affecting the base project. Branching also allows developers to work in a test environment that tracks progress and doesn’t affect production applications.
This guide shows you how to switch branches in your Git project.
Prerequisites
- A Git project
- A Linux system with access to a terminal window/command line
Switch Branch With Git Checkout Command
Access the command line and use the checkout
command to check out the branch you want to use:
git checkout [branch_label]
Replace [branch_label] with the actual name of the branch you want to access. For example:
git checkout bugfix224
You have successfully switched to the bugfix224 branch and can start working on it.
Create and Check Out a New Branch
If you need to open a new branch, use the checkout
command and add the –b
option. This command both creates and opens a new branch:
git checkout -b bugfix231
By default, the new branch is based on the last commit in the currently checked-out branch.
If you want to use a different source, specify that source as follows:
git checkout -b (new_branch)(source_branch)
This example basses the bugfix231 branch off the bugfix230 branch.
git checkout -b bugfix231 bugfix230
The output confirms that a new branch has been added and that you have switched to it.
The checkout
command can be used to create branches as well as individual files. This feature has led to unwanted results, especially when branches and files have similar names. The switch
command was introduced in Git version 2.23 as an attempt to simplify the process.
Note: Learn how to compare two Git branches.
Switch Branch With Git Switch Command
The switch
command was introduced in Git 2.23 and subsequent releases. The principle command structure is the same as with the checkout
command. Access the command line and use the switch
command to mount the branch you want to use:
git switch [branch_label]
Replace [branch_label] with the actual name of the branch you want to switch to.
For example:
git switch bugfix224
You have successfully switched to the bugfix224 branch and can start working on it.
Conclusion
You now know how to switch branches in your Git project. You are free to make changes to the branch’s code, add and test new features, and work on fixing bugs and glitches. Next, you should learn is how to set up a Git upstream branch, how to change it and how to have an overview of which Git branch is tracking which upstream branch.
Feel free to experiment as Git keeps records of committed changes. You can retrace your steps in case testing does not go as planned.