Git & GitHub - Branching in Git
Introduction to branching and how to create branches
Branching is a powerful feature in Git that allows you to create separate lines of development within a repository. This guide introduces the concept of branching and explains how to create and manage branches in Git.
Key Points:
- Branches allow you to work on different features or fixes simultaneously without affecting the main codebase.
- The
main
branch is typically the default branch in a repository. - Creating and switching branches is easy and enables isolated development and collaboration.
What is a Branch?
A branch in Git is a lightweight movable pointer to a commit. The default branch in a repository is usually called main
. When you want to add a new feature or fix a bug, you create a new branch to encapsulate your changes.
# View all branches in the repository
$ git branch
# Create a new branch
$ git branch new-feature
# Switch to the new branch
$ git checkout new-feature
Creating a Branch
To create a new branch, use the git branch
command followed by the name of the new branch. This creates a new branch but does not switch to it.
# Create a new branch named "new-feature"
$ git branch new-feature
Switching Branches
To switch to an existing branch, use the git checkout
command followed by the name of the branch. This updates your working directory to match the state of the selected branch.
# Switch to the "new-feature" branch
$ git checkout new-feature
Creating and Switching Branches
You can create a new branch and switch to it immediately using the git checkout -b
command. This is a shortcut that combines branch creation and switching.
# Create and switch to a new branch named "new-feature"
$ git checkout -b new-feature
Merging Branches
Once you have finished working on a branch, you can merge it back into the main branch using the git merge
command. First, switch to the branch you want to merge into (typically main
), then execute the merge command.
# Switch to the main branch
$ git checkout main
# Merge the "new-feature" branch into the main branch
$ git merge new-feature
Deleting Branches
After merging a branch and ensuring it is no longer needed, you can delete it using the git branch -d
command. This helps keep your repository clean and manageable.
# Delete the "new-feature" branch
$ git branch -d new-feature
If the branch has not been merged, you can force delete it using the git branch -D
command.
# Force delete the "new-feature" branch
$ git branch -D new-feature
Summary
This guide provided an introduction to branching in Git, including how to create, switch, merge, and delete branches. Branching is a fundamental feature in Git that enables parallel development and helps manage project workflows effectively.