Branching
A branch is a separate work space where you can make changes and experiment without affecting the main
project. Branches serve as an abstraction for the edit/stage/commit
process, allowing you to work on different parts of a project without touching the main branch.
Use Cases:
- Work safely on new features without affecting the main codebase
- Experiment with new ideas
- Fix bugs in isolation
- Collaborate without breaking the project
- Test features before merging into main
Examples:
Create a New Branch:
git branch [new branch]
List all branches:
Provides a list of all the current branches in your project.
git branch
[branch name]
* main
* main
The * next to main specifies the branch we are currently on.
Switch Between Branches:
-
Switch to another branch:
git switch [branch name]
-
You can also use:git checkout [branch name]Git switch and git checkout can be used to switch branches. Git switch is a safer command for branch operations only. Git checkout is a command with multiple functions, which can lead to confusion and potential loss of data if not used correctly.
-
You can create and switch to a new branch at the same time:git switch -c [branch name]
Delete a branch:
This deletes a branch that is no longer needed. This is typically used after a branch has been merged
when the work on the branch is done.
git branch -d {branch name}