Now suppose we want to amend a previous commit. To do this we need to use interactive rebasing. Remember that with rebasing we can replay a bunch of commits on top of other commits. The interactive part of the name means that we want to give Git instructions while doing it.
As an example, suppose we want to amend commit 8441b05. To do so, we need to supply its parent commit to Git. That is 8527033. So we run
git rebase -i 8527033
Git will open VS Code in a script that looks like the one below. In this script we can tell Git which operation we want to do for each commit. If you are using the GitLens extension then commits will appear in the same order as they would when running git log. So at the top you'll see the latest commit and at the bottom the commit we want to edit. Otherwise, at the top you'll see the commit that we want to edit and, at the bottom, the latest commit in this branch.
For each commit you can give an instruction. For this demo, we'll just edit one commit. So, we select the edit option from the dropdown menu.
When we close the VS Code window (or click on Start Rebase if you are using GitLens) the rebase operation will start.
Because we told Git that we wanted to edit commit 8441b05, Git stopped at that commit so that we can make our changes. We can amend this commit now.
In this case, we are just making changes to one file, but we could add or delete files if we needed to. When we are done, we stage our changes and commit them by running
git commit --amend
just as we would if we were amending the last commit.
If we take a look at the log, we see that we now have two branches. One with all the old commits that we are now rebasing (at its tip you can see the master pointer). The other branch is the one that we are creating with the interactive rebase.
Because we told Git that we wanted to edit this commit, the rebasing operation is waiting for us to tell it to continue. When we do, Git will replay all the other commits involved in the rebase on top of the new commit.
To continue with the rebase, we run
git rebase --continue
Since at the start of the rebase we told Git that we only wanted to edit that one commit, when we run continue, Git automatically took care of the other commits.
Once done rebasing all commits, Git moved the pointer of our branch (in this case master) to the tip of the new branch.
If at any pause during the rebase operation you decide that you don't want to go through with it, you can run
git rebase --abort
and Git will restore everything to the state before starting the rebase.