March 16, 2025
O. Wolfson
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:
shgit 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:
shgit 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:
shgit 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:
shgit add .
git rebase --continue
shgit rebase --abort
Follow this exercise to practice Git rebase in a controlled environment.
shmkdir git-rebase-exercise && cd git-rebase-exercise
git init
shgit checkout -b feature-branch
shecho "Initial content" > file.txt
git add file.txt
git commit -m "Initial commit on feature branch"
main
and add a change:
shgit 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:
shgit checkout feature-branch git rebase main
file.txt
and continue:
shgit add file.txt
git rebase --continue
shgit 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.