Merging and Rebasing
Duration: 8 min
What is Merging?
Merging combines changes from one branch into another. It's the most common way to integrate work from different branches in Git.
Creating and Switching Branches
Before merging, you need to create a branch to work on:
# Create a new branch
git branch feature/add-model
# Switch to the new branch
git checkout feature/add-model
# Or create and switch in one command
git checkout -b feature/add-model
# List all branches
git branch -a* feature/add-model
mainMaking Changes on a Branch
# Make some changes
echo 'def train_model():' >> model.py
echo ' pass' >> model.py
# Stage and commit
git add model.py
git commit -m 'Add train_model function'
# View the commit
git log --onelinea1b2c3d (HEAD -> feature/add-model) Add train_model function
e4f5g6h (main) Initial commitMerging Branches
Once your feature is ready, merge it back into main:
# Switch back to main
git checkout main
# Merge the feature branch
git merge feature/add-model
# View the merged history
git log --onelinea1b2c3d (HEAD -> main) Add train_model function
e4f5g6h Initial commitUnderstanding Rebasing
Rebasing is an alternative to merging. It replays your commits on top of another branch, creating a linear history.
# Create a new branch
git checkout -b feature/add-preprocessing
# Make changes and commit
echo 'def preprocess_data():' >> model.py
git add model.py
git commit -m 'Add preprocessing function'
# Rebase onto main
git rebase main
# View the linear history
git log --onelinea1b2c3d (HEAD -> feature/add-preprocessing) Add preprocessing function
e4f5g6h (main) Initial commitMerge vs Rebase
| Aspect | Merge | Rebase |
|---|---|---|
| History | Non-linear, shows branches | Linear, cleaner |
| Safety | Safer, preserves history | Rewrites history |
| Use Case | Team collaboration | Local cleanup |
💡 Tip: Use merge for shared branches, rebase for local branches before pushing.
❓ What does rebasing do?