Branches
Scope
This article introduces the concept of branches in the Git context and how users can create new and switch to existing branches via the Command Line Interface (CLI) and the RStudio IDE.
Introduction to Git Branches
Branches are one of the most useful features associated with Git. They enable developers to work on the same project in parallel without overwriting the others' changes. This is done by creating separate copies of the project referred to as branches
that developers can switch to and commit their changes.
By default, all repositories are initialized with a default branch named the main
or master
branch. Then, developers can switch to branches throughout the development process.
NOTE: Originally, the name of the initial default branch for a repository was master
, but that was recently changed to main
(as shown here in GitHub's documentation). This document refers to both, in case you are exposed to some older repositories still utilizing the master
branch as the repository's default branch.
Switching to a Branch
You can switch to a new/existing branch two ways.
Switching Branches via the CLI
Enter the following command in the CLI to switch to a new branch:
git checkout <branch_name>
Adding the -b
tag will create the branch if it doesn't exist. For example:
git checkout <branch_name> -b
Alternatively, if you know you are creating a new branch, you do so with the git branch
function, as shown here:
git branch <branch_name>
To view the current branch you are working on, type:
git branch
Switching Branches in RStudio
In RStudio, to create a new branch, click on the branch icon (circled in red) *below*.
To switch to a different existing branch, click on drop-down menu (circled in green) below.
Git Branching Flow
Generally as developers, the default workflow of Git is to make any changes/commits in separate branches which are then merged into the main
/ master
branch via a .
This prevents unverified/untested code from making it into the main
/master
branch, causing future developers to work off of broken code.
It also helps isolate development work as two developers do not have to worry about breaking each other's code with their changes.
This concept is covered in more details in the Merging KB article.