🧱
Git basics: rebase
on programminglast updated 3/14/21
Rebasing is the process of squashing, or combining, multiple related commits into a single, base commit. Similar to merging, rebasing integrates changes from one branch into another branch.
While git merge
will preserve project history, a git rebase
command rewrites it. Rebasing helps with maintaining a clear, succinct history of commits.
Branches without collaborators are typically fine to rebase but if you’re working with others, you may want to merge the branch instead.
A workflow where rebasing might make sense could look like this:
- You create and checkout a new branch locally.
- Make changes locally.
- Commit and push changes.
- Repeat steps 2 and 3 on the same branch.
- You realize your multiple commits should be combined into a single commit.
To begin the rebase process, you’ll want to pull in the most recent version of the branch you were working on.
For example, if you pulled in the qa
branch for a repo called backend-dev
, created a new branch off that locally, and pushed commits for the new branch, you should checkout the qa
branch, pull in the most recent version of it, and then checkout your new branch again.
If you’re unfamiliar with the difference between git fetch
and git pull
, this may help: https://stackoverflow.com/questions/292357/what-is-the-difference-between-git-pull-and-git-fetch.
Now run git rebase -i your-original-branch-name
. Including the -i
flag in this command will open an editor with a list of all of the commits you made on the new branch.
If you're unfamiliar with VIM, here are two commands you'll need:
- To edit: type
i
- To save changes and exit: press
ESC
, type:wq
, and pressENTER
Each line corresponds to a separate commit; pick
means keep the commit and squash
means combine the commit. To combine all of the commits into a single commit, set pick
for the first line and change all other lines to squash
.
Your editor should now look something this:
pick 07c5abd the commit we want to keep
squash de9b1eb a commit we want to combine
s 3e7ee36 s is just an abbreviation for squash
s fa20af3 we can also use p as an abbreviation for pick
Upon saving these changes and exiting VIM, you’ll be met with the option to rewrite the joint commit message.
By default, this will aggregate the commit messages from all of the commits you’re combining, with each message on a separate line. Feel free to edit for clarity before again saving and exiting VIM.
To push your rebased branch, finally run git push origin your-original-branch-name --force
.
Following the linked pull request (or merge request if you're using GitLab, it's the same feature) in your terminal's output, you should see that your multiple commits have been squashed into a single, base commit.