Git Branch Basics
Understanding Git Branches
Git branches are fundamental to version control, allowing developers to create independent lines of development within a repository. A branch represents an isolated workspace where you can make changes without affecting the main project.
Core Concepts of Branches
Branches in Git enable parallel development by providing a mechanism to:
- Experiment with new features
- Fix bugs in isolation
- Manage different project versions
gitGraph
commit
branch feature-login
checkout feature-login
commit
commit
checkout main
merge feature-login
Creating and Managing Branches
Command |
Description |
git branch |
List all local branches |
git branch <name> |
Create a new branch |
git checkout <branch> |
Switch to a specific branch |
git checkout -b <branch> |
Create and switch to a new branch |
Practical Example on Ubuntu 22.04
## Initialize a new repository
git init my-project
cd my-project
## Create a new branch
git branch feature-authentication
git checkout feature-authentication
## Make changes
touch login.py
echo "def authenticate_user():" > login.py
echo " ## Authentication logic" >> login.py
## Commit changes
git add login.py
git commit -m "Add authentication feature"
## Return to main branch
git checkout main
This example demonstrates creating a branch, making changes, and understanding basic branch workflow in a Git repository.