Combine multiple older commits into one

Viewed 58

I currently have a branch which looks like the following (with A being the most recent commit and K being the oldest, many months ago)

A-B-C-D-E-F-G-H-J-K   (branch-alpha)

What I would like to do is replace commits D-G with Z so that the resulting branch looks like so

A-B-C-Z-H-J-K   (branch-alpha)

All the examples I could find refer to combining the most recent commits, but I want to keep the most recent 3 commits are they are. I want to combine commits number 4, 5, 6, 7, all into one. How can I achieve this?

1 Answers

assuming A - K is the last 10 commits, you can run the command

git rebase -i HEAD~10

which opens the "interactive" => -i command prompt editor (with the last 10 commits) looking something like:

pick a2260e9 A
pick ff5e839 B
pick 965d9ea C
pick b09f2ae D
pick d1c9f15 E
pick 93309a9 F
pick e17d8fd G
pick d10491b H
pick 110c55f J
pick b57bc16 K

# Rebase ae65653..b57bc16 onto ae65653
#
# 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
#  f, fixup = like "squash", but discard this commit's log message
#  x, exec = run command (the rest of the line) using shell
#
# These lines can be re-ordered; they are executed from top to bottom.
#
# If you remove a line here THAT COMMIT WILL BE LOST.
#
# However, if you remove everything, the rebase will be aborted.
#
# Note that empty commits are commented out

you then change the following lines from pick to s for "squash"

pick a2260e9 A
pick ff5e839 B
pick 965d9ea C
pick b09f2ae D
s d1c9f15 E
s 93309a9 F
s e17d8fd G
pick d10491b H
pick 110c55f J
pick b57bc16 K

Save the file. On the next screen it will ask you about the commit message. Add a # on every line which has not got a # yet. That will then be treated as a comment. Add one line with only a Z that will then be the commit message for the squashed commits

the end result looks like:

a2260e9 A
ff5e839 B
965d9ea C
38e9fab Z
553c8c7 H
23acc30 J
143561a K
Related