Git Branch Basics
Understanding Git Branches
Git branches are lightweight, movable pointers to specific commits in your repository. They allow developers to work on different features or experiments simultaneously without affecting the main codebase.
Branch Concepts
What is a Branch?
A branch represents an independent line of development. When you create a branch, Git creates a new pointer to the current commit you're on.
gitGraph
commit
commit
branch feature
checkout feature
commit
commit
checkout main
commit
Default Branch
By default, Git creates a main
(or master
) branch when you initialize a new repository.
Basic Branch Commands
Command |
Description |
git branch |
List all local branches |
git branch <branch-name> |
Create a new branch |
git branch -d <branch-name> |
Delete a branch |
Creating and Switching Branches
Creating a New Branch
## Create a new branch
git branch feature-login
## Create and switch to a new branch
git checkout -b feature-payment
Viewing Branches
## List local branches
git branch
## List all branches (local and remote)
git branch -a
Branch Workflow Example
## Initialize a new repository
git init
## Create a new feature branch
git checkout -b feature-authentication
## Make some changes
touch login.py
git add login.py
git commit -m "Add login functionality"
## Switch back to main branch
git checkout main
Best Practices
- Use descriptive branch names
- Keep branches focused on specific features
- Regularly merge or rebase to keep branches updated
LabEx Tip
When learning Git branches, LabEx provides interactive environments to practice these concepts hands-on.