Git rebase is a powerful tool that helps you update your branch by applying its changes on top of another branch, typically the latest version of main or develop. Unlike git merge, which creates a new merge commit, rebasing keeps the commit history cleaner and more linear.
If you're working on a feature branch and the main branch has new updates, rebase your branch before merging:
git checkout feature-branch
git fetch origin
git rebase origin/main
This applies your commits on top of the latest main branch.
If you’ve made multiple commits that should be combined into one, use interactive rebase:
git rebase -i HEAD~3 # Squashes the last 3 commits
Then, choose squash (or s) for commits you want to merge.
Instead of merging a feature branch, you can rebase to keep history linear:
git checkout main
git pull origin main
git checkout feature-branch
git rebase main
If you encounter conflicts, Git will pause the rebase and prompt you to resolve them:
git add .
git rebase --continue
git rebase --abort
Follow this exercise to practice Git rebase in a controlled environment.
mkdir git-rebase-exercise && cd git-rebase-exercise
git init
git checkout -b feature-branch
echo "Initial content" > file.txt
git add file.txt
git commit -m "Initial commit on feature branch"
main and add a change:
git checkout main
echo "Main branch update" > file.txt
git add file.txt
git commit -m "Update from main branch"
feature-branch and start the rebase:
git checkout feature-branch
git rebase main
file.txt and continue:
git add file.txt
git rebase --continue
git log --oneline --graph
Git rebase is a great tool for keeping your commit history clean and avoiding unnecessary merge commits. However, it should be used carefully to avoid disrupting shared branches. By understanding when and how to use it, you can work more efficiently and keep your Git history readable.