📅 2020-Jun-19 ⬩ ✍️ Ashwin Nanjappa ⬩ 🏷️ git, rebase ⬩ 📚 Archive
The interactive rebase in Git is one of its coolest features. It allows you to reorder, squash, delete and rename commits.
Since this feature allows you to change history, make sure to use it to only modify sections of the local DAG that have not yet been pushed to a remote. Do not use it to change parts of the DAG that are already in the remote and possibly already fetched by other people.
Interactive rebase requires a revision from you as input. Here are some examples:
$ git rebase -i HEAD~3
$ git rebase -i foobar_branch
$ git rebase -i foobar_tag
$ git rebase -i c35d286
Git will open your editor and display all the commits newer than the revision that you provided. These are the commits that you wil be allowed to manipulate.
Here is an example of what Git might show you:
pick 0083bd5 Some third commit
pick a0303c4 This is fourth commit
pick 19bfef8 I guess this is fifth commit
Remember that the commits are ordered from old to new as you go from top to bottom.
Here are the operations you can do on this commit list and then save-quit the file:
Remove a commit: Delete the lines having the commits you want to drop. Or replace the pick
of the commit line with d
or drop
. After you save the file, these commits are gone from the Git DAG.
Rename a commit: Replace pick
of the commit line with r
or reword
. After you save the file, Git will pop up editors for each of the reword commits, giving you the opportunity to change those commit messages.
Reorder commits: Reorder the commit lines and save the file. Your Git DAG will now have the order you chose.
Squash commits - keeping oldest commit message: You want to combine two or more commits into a single commit, but want to retain the message of the oldest of those commits for the final combined commit. To achieve this, replace pick
of all the newer commits, except the old commit, with f
or fixup
. After you save the file, you now have a single commit with the commit message of the oldest commit.
Squash commits - with a new commit message: Replace pick
of all the newer commits with s
or squash
. After you save the file, Git will pop up an editor allowing you to provide the commit message of the new combined commit. The editor will have the commit messages of the constituents, giving you a chance to reuse those to make your new commit message. Whatever you leave uncommented will be the new commit message.
You can repeat and mix and match any of the above operations any number of times to do plastic surgery on your DAG until it looks perfect like you want it to.
Tried with: Git 2.17.1 and Ubuntu 18.04