Git Branching
A branch is a divergence from the main line of development. In other words, if a Git repository is a straight line, a branch is a second line that splits and runs parallel from the first.
Creating a Branch
In Git, a branch can be created using the git branch command. While the git branch command accepts many options, to create a new branch, follow the command with the desired name of the new branch.
git branch new-branch
Switching Branches
When the Git repository is first initialized, a default branch is created. This branch is usually called main or master (Learn How to set the name of the default branch). But once a second or multiple branches are created, it may become necessary to switch to an alternate branch. Switching can be accomplished by using the git checkout command.
git checkout new-branch
Listing Branches
When the git branch command is run without any arguments, it will list all branches of the current repository. The * character indicates the branch that is currently checked out.
git branch
Adding the -v option will include the last commit on each branch.
git branch -v
Merging Branches
Merging is a vital part of working with branches, and therefore it is helpful to know which branches have been merged. The --merged option will list branches that have already been merged. While the --no-merged option lists those branches that have yet to be merged.
git branch --merged
Deleting Branches
Once a branch has been merged and is no longer needed, the branch can be deleted. To delete a branch, the -d option is applied to the git branch command followed by the name of the branch to be deleted.
git branch -d new-branch
NOTE
The command above will fail when deleting the currently checked out branch. If the branch has not been fully merged, Git will require the force delete option (-D) to delete the branch.
Renaming Branches
The --move option can be used to rename an existing branch.
# renames master branch to main locally
git branch --move master main
The renamed branch must be pushed to the remote repository to change the branch name remotely.
git push --set-upstream origin main
However, this will cause both the master and the main branches to appear on the remote repository. To entirely remove the master branch from the remote repository, the following command should be used.
git push origin --delete master
This YouTube video was created by GitHub Training & Guides.