Branching is the core concept that makes Git such a powerful tool for collaboration and development. A branch is essentially an independent line of development that moves forward while the main project remains stable.
1. What is a Branch?
A branch is a lightweight, movable pointer to one of your commits. When you create a branch, Git simply creates a new pointer that refers to the same commit the current branch is pointing to. [Image illustrating a main commit history line with a separate, new branch pointer diverging from the main line]
- Master/Main Branch: The primary, stable line of development (often called
mainormaster). Commits here should represent releases or highly stable versions. - Feature Branches: Branches created for isolated work (e.g.,
feature/login-page,bugfix/auth-issue). This allows developers to work without interfering with the main code base.
2. Basic Branch Commands
| Action | Command | Purpose |
| List Branches | git branch | Lists all local branches in your repository. The active branch is typically marked with an asterisk (*). |
| List Remote Branches | git branch -r | Lists branches on the remote repository (e.g., GitHub). |
| List All Branches | git branch -a | Lists both local and remote branches. |
Execution Examples
To list all local branches:
git branch
3. Creating and Switching Branches
When starting a new feature or bug fix, you should always create a new branch from a stable point (usually main).
Creating a New Branch
To create a new branch named new-feature but remain on your current branch (main):
git branch new-feature
Switching Branches (git checkout or git switch)
To switch your working directory and history pointer to the new branch:
# Old (still works)
git checkout new-feature
# New (recommended for clarity)
git switch new-feature
Creating and Switching Simultaneously
The -b flag with git checkout is the most common shortcut for creating a new branch and switching to it in one step.
git checkout -b new-feature
4. Making a Commit on a Branch
Once you are on a new branch (e.g., new-feature), all subsequent commits you make will only move the new-feature pointer forward. The main branch pointer remains where it was, preserving its history.
Example Workflow
- Create and switch to the new branch.
git checkout -b new-styling - Make file changes (e.g., modify
style.css). - Stage and commit the changes.
git add . git commit -m "Implement new color palette in CSS" - The
new-stylingbranch now points to this new commit. Themainbranch is unaffected.
