Branching
Branching
Create branches to work on features independently and merge them back when done.
Branches
A branch is a pointer to a specific commit. Creating a branch is fast and cheap in Git.
The default branch is usually called main (formerly master).
Branching Workflow
- Create a branch for a feature or bug fix
- Make commits on that branch
- Merge the branch back into
mainwhen done
Fast-forward vs 3-way Merge
- Fast-forward: If
mainhasn't changed, Git just moves the pointer forward - 3-way merge: Creates a new merge commit combining two diverged histories
Merge Conflicts
When two branches change the same lines, Git can't auto-merge — you must resolve conflicts manually.
Example
bash
# List all branches
git branch # local branches
git branch -a # all branches including remote
# Create and switch to a new branch
git checkout -b feature/user-auth
# Modern syntax (Git 2.23+):
git switch -c feature/user-auth
# Switch branches
git checkout main
git switch main
# Make commits on the feature branch
git add .
git commit -m "Add login form component"
git commit -m "Add authentication API calls"
# Merge feature branch into main
git switch main
git merge feature/user-auth
# Delete merged branch
git branch -d feature/user-auth
# Resolving merge conflicts:
# 1. Git marks conflicts in files with <<<<<<, =======, >>>>>>>
# 2. Edit the file to resolve
# 3. git add the resolved file
# 4. git commit to complete the merge
# Rebase (alternative to merge - cleaner history)
git switch feature/my-feature
git rebase main # replay commits on top of main
# Interactive rebase (cleanup commits)
git rebase -i HEAD~3 # squash/edit last 3 commitsTry it yourself — BASH