How to rebase selected commits interactively (Git)

Reginald LynchOctober 30th 2020, 5:10

When you are working on a new feature and have branched from an old release into a feature branch, you might want to rebase this branch onto the latest release. When looking into the list of commits on the feature branch, you may realize that some of the commits are not suitable for the new release. In that case, when you want to rebase the branch onto a new release, you will need to remove some commits. This can be achieved with interactive rebasing, where Git gives you the option to pick the commits you wish to rebase.

Step 1 : To get started with this example, you need to check the previously created branch, rebaseExample; if you don't have this branch, follow the steps from the Rebasing commits to another branch section and use the following command:

git checkout rebaseExample

Step 2 : Rebase the branch onto origin/stable-3.1 by using the following command:

git rebase --interactive origin/stable-3.1

What you will see now is a list of all the commits you will be rebasing onto the origin/stable-3.1 branch. These commits are all the commits between the origin/stable-3.1 and rebaseExample branches. The commits will be applied from top to bottom, hence, the commits will be listed in reverse order—at least compared to what you would normally see in Git. This actually makes good sense. The commits have the keyword pick to the left and then the abbreviated commit hash, and finally the title of the commit subject.

Step 3 : Remove all the lines except for the two commits at the bottom; for now, leave pick as the keyword. Save the file and close the editor, and you will get the following message from Git:

Step 4 : Now, with gitk, check whether we accomplished what we predicted. The next screenshot shows our two fishtank commits on top of the origin/stable-3.1 branch. The following screenshot is what we expected: