How to use interactive rebase on the first (root) commit of a branch?

Shubham Chaudhary picture Shubham Chaudhary · May 16, 2015 · Viewed 9.3k times · Source

If I'm in the following situation,

$ git log --oneline
* abcdef commit #b
* 123456 commit #a

I know I can always run

$ git reset HEAD~ 
$ git commit --amend

However, I tried to run

$ git rebase -i HEAD~2

but I got

fatal: Needed a single revision
invalid upstream HEAD~2

Hence my question: is there a way to use git rebase to squash these two commits or not?

Answer

jub0bs picture jub0bs · May 16, 2015

You want to rebase to the root commit of your master branch. More specifically, to squash the two commits, you need to run

git rebase -i --root

and then substitute squash for pick on the second line in the buffer of the editor that pops up:

pick 123456 a                                                        
squash abcdef b

I refer you to the git-rebase man page for more details about that flag:

--root

Rebase all commits reachable from <branch>, instead of limiting them with an <upstream>. This allows you to rebase the root commit(s) on a branch. [...]

Example of an interactive rebase of the root

# Set things up
$ mkdir testgit
$ cd testgit
$ git init

# Make two commits
$ touch README
$ git add README
$ git commit -m "add README"
$ printf "foo\n" > README
$ git commit -am "write 'foo' in README"

# Inspect the log
$ git log --oneline --decorate --graph
* 815b6ca (HEAD -> master) write 'foo' in README
* 630ede6 add README

# Rebase (interactively) the root of the current branch: 
# - Substitute 'squash' for 'pick' on the second line; save and quit the editor.
# - Then write the commit message of the resulting commit; save and quit the editor.
$ git rebase -i --root
[detached HEAD c9003cd] add README; write 'foo' in README
 Date: Sat May 16 17:38:43 2015 +0100
 1 file changed, 1 insertion(+)
 create mode 100644 README
Successfully rebased and updated refs/heads/master.

# Inspect the log again
$ git log --oneline --decorate --graph
* c9003cd (HEAD -> master) add README; write 'foo' in README