2

I have the following commits in my branch.

  1. last commit
  2. third commit
  3. second commit
  4. first commit

How could I combine commit 3 and 2 but with commit message of commit 2. This is the result I will be expecting

  1. last commit
  2. second commit (3 is combined to 2)
  3. first commit
phd
  • 82,685
  • 13
  • 120
  • 165
tsadkan yitbarek
  • 1,360
  • 2
  • 11
  • 28
  • 1
    Does this answer your question? [Combining multiple commits before pushing in Git](https://stackoverflow.com/questions/6934752/combining-multiple-commits-before-pushing-in-git) – phd Apr 21 '20 at 08:59
  • https://stackoverflow.com/search?q=%5Bgit%5D+combine+commits – phd Apr 21 '20 at 08:59

2 Answers2

7

you can do this interactively using

git rebase -i HEAD~4

then you will see an editor like

pick <sha-1> commit 1
pick <sha-2> commit 2
pick <sha-3> commit 3
pick <sha-4> commit 4

which you need to change to:

pick <sha-1> commit 1
pick <sha-2> commit 2
fixup <sha-3> commit 3
pick <sha-4> commit 4

save and quit, and that's it.

Chris Maes
  • 35,025
  • 12
  • 111
  • 136
1
  • git rebase -i <sha key of first commit>
  • An editor will be opened. Change pick to squash at second and third commit
  • Write and quit
  • The editor will pop up again for you to write the new commit message.
emremrah
  • 1,733
  • 13
  • 19
  • 1. no need to run git commit after "write and quit". 2. fixup does automatically what he wants, why complicating things with squash. 3. what does your answer add to mine? – Chris Maes Apr 21 '20 at 07:52
  • Thank you for pointing these up. It's an alternative answer. Your answer is pointing `fix`, mine is `squash`. – emremrah Apr 21 '20 at 07:56
  • Fair enough, although it is more compliated. Still your answer is wrong since there is no need to run `git commit`after "write and quit". – Chris Maes Apr 21 '20 at 08:02
  • Yep I remembered that way but was unable to try it first. I'm investigating it. – emremrah Apr 21 '20 at 08:03
  • @Chris fixup does not "combine" the commits, only readies it for `autosquash` (you can add that to your rebase line with `--autosquash`). I would go with this solution but for no particular reason. There is no extra overhead whatsoever, simply a "s" where you put a "fixup". Perhaps if you prefer not combining the commit messages fixup is a better option marginally. Of course if you want it then squash is the only option. – kabanus Apr 21 '20 at 09:13
  • 1
    @kabanus you are mixing up "fixup commits" and the "fixup" directive when rebasing interactively. From the help in the editor: **f, fixup = like "squash", but discard this commit's log message** – Chris Maes Apr 21 '20 at 09:23
  • @emremrah `Change pick to squash at second and third commit` This will squash 1, 2 & 3. OP wants to squash only 2 & 3. – Emil M George Apr 21 '20 at 14:07