Branches in Git are a powerful feature that allow you to work on different parts of a project simultaneously without affecting the main codebase. This page explains the basics of branches and how to use them effectively.
A branch in Git is a pointer to a specific commit in your project’s history. It enables you to:
- Develop features or fix bugs in isolation.
- Experiment without disrupting the main codebase.
- Collaborate on separate tasks within a team.
When you initialize a Git repository, a default branch is created. It is usually named main
or master
.
- Isolation: Keep changes for new features or bug fixes separate from the main project.
- Collaboration: Multiple team members can work on different branches simultaneously.
- Versioning: Easily switch between different versions or states of your project.
To list all branches in your repository:
git branch
To create a new branch:
git branch branch_name
To move to an existing branch:
git checkout branch_name
Or, create and switch to a new branch in one command:
git checkout -b branch_name
To rename the branch you are currently on:
git branch -m new_branch_name
To delete a branch locally:
git branch -d branch_name
Use -D
to force-delete a branch:
git branch -D branch_name
Merging integrates changes from one branch into another. For example, merging a feature branch into main
:
-
Switch to the target branch:
git checkout main
-
Merge the feature branch:
git merge feature_branch
If there are conflicts during merging:
- Open the affected files and resolve the conflicts.
- Mark conflicts as resolved:
git add file_with_conflicts
- Complete the merge:
git commit
To see a graphical view of branches and commits:
git log --oneline --graph --all
- Use Descriptive Names: Name branches based on their purpose, e.g.,
feature/user-auth
orbugfix/login-error
. - Work Incrementally: Make small, manageable changes on branches.
- Keep
main
Stable: Only merge tested and working code into the main branch. - Regularly Sync with
main
: Pull the latest changes frommain
into your branch to avoid large conflicts.
Command | Description |
---|---|
git branch |
List all branches. |
git branch branch_name |
Create a new branch. |
git checkout branch_name |
Switch to an existing branch. |
git checkout -b branch_name |
Create and switch to a new branch. |
git merge branch_name |
Merge a branch into the current branch. |
git branch -d branch_name |
Delete a branch. |
git log --oneline --graph --all |
View a graphical history of branches. |
git checkout -b feature/new-feature
echo "New feature code" > feature.txt
git add feature.txt
git commit -m "Add new feature"
git checkout main
git merge feature/new-feature
git branch -d feature/new-feature
Branches are an essential part of Git workflows, allowing you to isolate changes, collaborate with others, and maintain a clean and stable codebase. Mastering branch management is key to efficient version control.
Next Steps: Merging Changes