21

Can we use rebase to squash multiple commits into one single commit on the same branch?

Taking an example, i have created two topic branches - issueA_1 and issueA_2 from master. I make a couple of commits in both branches, as can be seen in the diagram(i am using commit names here instead of commit hashes for brevity) :

 --> (issueA_1) - commitX1 / (master)-- \ --> (issueA_2) | commitY1 | commitY2 

Then i do :

git checkout issueA_2 git rebase -i issueA_1 

I change the rebase file to :

pick commitY1 fixup commitY2 

After this rebase, the commit history looks like this :

 --> (issueA_1) - commitX1 / (master)-- \ --> (issueA_2) | commitX1 | commitY1 | commitY2 

I don't need the branch issueA_1 anymore, so i do :

git branch -D issueA_1 

The commit history of issueA_2 isn't pretty enough to be merged into master yet. I want commitX1, commitY1 and commitY2 of this branch to be squashed into 1 single commit before i merge into master. Is this possible?

1

2 Answers 2

43

Yes, the simplest way I find is to do:

git rebase -i HEAD~3 

This will let you review the last 3 commits and you can then squash them.

Sign up to request clarification or add additional context in comments.

2 Comments

Using this command I get the following text on my command window - pick <commit_id_1> <comment_1 written while committing> pick <commit_id_2> <comment_2 written while committing> # Rebase 551a895..4a2dc5e onto 551a895 (2 commands) # # Commands: # p, pick <commit> = use commit # r, reword <commit> = use commit, but edit the commit message # e, edit <commit> = use commit, but stop for amending # s, squash <commit> = use commit, but meld into previous commit ..... and so on. I'm unable to type any command mentioned on that window.
@phougatv You probably need to use vim commands. Press i to enter interactive mode then change the list of commits as described. Press esc to exit interactive mode then press :x to exit and save.
3

In your case,

git checkout issueA_2 git rebase -i master 

or

git rebase -i commitX1^ #parent of commitX1 in branch issueA_2 

should also work. In this case, you don't need to count (I'm usually one off).

4 Comments

what is git co? Did you mean git checkout ?
Would "commitX1^" be identical to "HEAD~3" in this context?
Yes, if I have counted that correcly ;)
ok. How could i have missed "git rebase -i master"! That was the simplest and safest option. I guess i was a little nervous thinking of rebase and master in the same line..it didn't strike me that the command does not effect the master branch at all.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.