git rebase
git rebase: reapply commits from one branch on top of another branch.
The git rebase command is used to move or combine a sequence of commits to a new base commit. Unlike git merge, which creates a merge commit to combine two branches, rebasing takes the commits from your current branch and replays them on top of another branch, creating a linear commit history.
Rebasing is particularly useful for maintaining a clean, linear project history. Instead of creating a "commit salad" where commits from different branches are interleaved, rebasing ensures that your feature commits appear as if they were developed directly on top of the latest changes from the target branch.
There are two main types of rebasing:
-
Regular rebase (default):
- Look for a common ancestor commit between your current branch and the target branch.
- Temporarily save your commits that are unique to your current branch.
- Move your current branch pointer to the latest commit of the target branch.
- One-by-one, reapply your saved commits on top of the target branch's latest
Effectively, this makes it look like you started your branch from the latest commit on the target branch rathern than from the commit in the past where you originally branched off.
-
Interactive rebase (
git rebase -i): Presents you with the interface, where you can edit, reorder, squash, or drop commits during the rebase process. Arguably the most powerful feature of Git.
Rebasing rewrites commit history by creating new commits with the same changes but different commit hashes. This means you should never rebase commits that have been shared with others, as it can cause confusion and conflicts for collaborators.
Pulling with rebase
By default, running git pull is effectively a combination of git fetch followed by git merge. The merge step may create a useless merge commit in the current branch. Do it several times in the process of developing a feature, and you end up with a messy commit history, which will make the final merge especially tricky.
What you really want is to take the latest changes from the remote branch and put all of your recent commits on top of it. This can be achieved with git pull --rebase.
But adding that option every time is tedious, so you can set rebase on pull as the default behavior for your repository:
git config pull.rebase trueExamples
(useful when you are on a feature or other branch) Rebase the current branch onto main:
git rebase mainStart an interactive rebase for the last 3 commits (for example, to reorder them or squash them into a single commit):
git rebase -i HEAD~3Continue a rebase after resolving conflicts:
git add .git rebase --continue
Abort a rebase and return to the original state:
git rebase --abortUpdate your current branch with the latest changes from main (take the main branch and put all of your commits on top of it):
git fetch origingit rebase origin/main
Set rebase as the default behavior for git pull:
git config pull.rebase true