One of the greatest feature of git rebase -i is recordering git commits. Be careful, you’d better do this before pushing these commits to remote, otherwise, it will make the merge non fast-forwardable and cause unexpected conflicts with other developers. Ok, now let’s see how to use it with an example.

Example

Supposing we have the following commits:

1
2
3
4
5
* 0d70c6e (HEAD -> master) Migrate more articles from old blogs.
* 7110c3f Add 404 page.
* 4146959 Add about page.
* 11a99be Update sitemap.
* ...

Let’s start by using git rebase -i HEAD~3, your editor will pop open with some text similar like this:

1
2
3
4
5
6
7
8
9
10
11
12
pick 4146959 Add about page.
pick 7110c3f Add 404 page.
pick 0d70c6e Migrate more articles from old blogs.
# Rebase 11a99be..0d70c6e onto 60709da (3 command(s))
#
# Commands:
# p, pick = use commit
# r, reword = use commit, but edit the commit message
# e, edit = use commit, but stop for amending
# s, squash = use commit, but meld into previous commit
#

Recordering is as simple as moving the pick commands around. For example, if you want to switch the commit 4146959 and 0d70c6e, simply switch the first line and the tird line.

1
2
3
4
5
6
7
8
9
10
11
12
pick 0d70c6e Migrate more articles from old blogs.
pick 7110c3f Add 404 page.
pick 4146959 Add about page.
# Rebase 11a99be..0d70c6e onto 60709da (3 command(s))
#
# Commands:
# p, pick = use commit
# r, reword = use commit, but edit the commit message
# e, edit = use commit, but stop for amending
# s, squash = use commit, but meld into previous commit
#

Save the file and exit, if everything goes well you would see the commit log as below. Magic, right? One thing you should keep in mind, it can not guarantee that every rebase will work without manual modification. Sometimes it will get messed up if some of the commits touched the same file. If this gets too messy to take care of, just do a git rebase –abort and you’ll be back where you started.

1
2
3
4
5
* 4146959 (HEAD -> master) Add about page.
* 7110c3f Add 404 page.
* 0d70c6e Migrate more articles from old blogs.
* 11a99be Update sitemap.
* ...