This example aims to describe how one can utilize
git rebase in interactive mode. It is expected that one has a basic understanding of what
git rebase is and what it does.
Interactive rebase is initiated using following command:
git rebase -i
-i option refers to interactive mode. Using interactive rebase, the user can change commit messages, as well as reorder, split, and/or squash (combine to one) commits.
Say you want to rearrange your last three commits. To do this you can run:
git rebase -i HEAD~3
After executing the above instruction, a file will be opened in your text editor where you will be able to select how your commits will be rebased. For the purpose of this example, just change the order of your commits, save the file, and close the editor. This will initiate a rebase with the order you've applied. If you check
git log you will see your commits in the new order you specified.
Now, you've decided that one of the commit messages is vague and you want it to be more descriptive. Let's examine the last three commits using the same command.
git rebase -i HEAD~3
Instead of rearranging the order the commits will be rebased, this time we will change
pick, the default, to
reword on a commit where you would like to change the message.
When you close the editor, the rebase will initiate and it will stop at the specific commit message that you wanted to reword. This will let you change the commit message to whichever you desire. After you've changed the message, simply close the editor to proceed.
Besides changing the commit message you can also adapt the changes done by the commit. To do so just change
edit for one commit. Git will stop when it arrives at that commit and provide the original changes of the commit in the staging area. You can now adapt those changes by unstaging them or adding new changes.
As soon as the staging area contains all changes you want in that commit, commit the changes. The old commit message will be shown and can be adapted to reflect the new commit.
Say you've made a commit but decided at a later point this commit could be split into two or more commits instead. Using the same command as before, replace
edit instead and hit enter.
Now, git will stop at the commit you have marked for editing and place all of its content into the staging area. From that point you can run
git reset HEAD^ to place the commit into your working directory. Then, you can add and commit your files in a different sequence - ultimately splitting a single commit into n commits instead.
Say you have done some work and have multiple commits which you think could be a single commit instead. For that you can carry out
git rebase -i HEAD~3, replacing
3 with an appropriate amount of commits.
This time replace
squash instead. During the rebase, the commit which you've instructed to be squashed will be squashed on top of the previous commit; turning them into a single commit instead.