Git Branch Basics
What is a Git Branch?
A Git branch is a lightweight movable pointer to a specific commit in the repository's history. Branches allow developers to work on different features or fixes simultaneously without interfering with the main codebase.
Creating a New Branch
To create a new branch in Git, use the following command:
## Create a new branch
git branch feature-login
## Create and switch to a new branch
git checkout -b feature-payment
Branch Naming Conventions
Branch Type |
Naming Convention |
Example |
Feature |
feature-* |
feature-user-authentication |
Bugfix |
bugfix-* |
bugfix-login-error |
Hotfix |
hotfix-* |
hotfix-security-patch |
Listing Branches
## List local branches
git branch
## List all branches (local and remote)
git branch -a
Switching Between Branches
## Switch to an existing branch
git checkout main
## Create and switch to a new branch
git checkout -b feature-dashboard
Branch Visualization
gitGraph
commit
branch feature-login
checkout feature-login
commit
commit
checkout main
merge feature-login
Best Practices
- Keep branches short-lived
- Use descriptive branch names
- Merge or rebase regularly
- Delete merged branches
At LabEx, we recommend following these best practices to maintain a clean and organized Git workflow.
Common Branch Operations
## Delete a local branch
git branch -d feature-login
## Force delete an unmerged branch
git branch -D feature-login
## Rename a branch
git branch -m old-name new-name