Git rebase is a powerful command for rewriting comit history. Below are two common scenarios where it proves especially useful: applying one branhc's commits onto another and removing or altering specific commits.
Bringing Changes from One Branch into Another
Suppose you have two branches: main and feature-x. Both have diverged with shared and unique commits. You want to apply the commits that exist only on main onto feature-x. The following steps accomplish that:
- Switch to
main: ``` git switch main - Rebase the current branch (
main) interactively ontofeature-x. The-iflag lets you review each commit individually: ``` git rebase -i feature-x - During the rebase you may encounter merge conflicts. Resolve them as they appear, then continue the rebase with
git rebase --continue. After all conflicts are resolved,mainnow has its unique commits placed on top offeature-x. The branch pointer remains onmain. - Switch back to
feature-x: ``` git switch feature-x - Finally, merge
mainintofeature-x. This is typically a fast‑forward merge becausemainis now a direct descendant offeature-x: ``` git merge main
With feature-x up to date, you can push it to the remote.
Deleting or Editing a Specific Commmit
Consider a branch with commits alpha, beta, gamma, delta, epsilon, zeta. The commit delta is problematic and you want to remove it entirely. Use interactive rebase:
git rebase -i gamma
This command opens an editor listing the commits from gamma onwards (i.e., delta, epsilon, zeta). The instructions in the editor show:
# Commands:
# p, pick = use commit
# r, reword = use commit, but edit the commit message
# e, edit = use commit, but stop for amending
# s, squash = use commit, but meld into previous commit
# f, fixup = like "squash", but discard this commit's log message
# x, exec = run command (the rest of the line) using shell
# d, drop = remove commit
To delete delta, change its line from pick to drop (or simply delete the line). Save and exit the editor. Git will replay the remaining commits, effectively removing delta. After the rebase, the branch contains only alpha, beta, gamma, epsilon, zeta.
You can also use edit or reword to modify commit content or messages, respectively.