Commits can be squashed during a git rebase
. It is recommended that you understand rebasing before attempting to squash commits in this fashion.
Determine which commit you would like to rebase from, and note its commit hash.
Run git rebase -i [commit hash]
.
Alternatively, you can type HEAD~4
instead of a commit hash, to view the latest commit and 4 more commits before the latest one.
In the editor that opens when running this command, determine which commits you want to squash. Replace pick
at the beginning of those lines with squash
to squash them into the previous commit.
After selecting which commits you would like to squash, you will be prompted to write a commit message.
Logging Commits to determine where to rebase
> git log --oneline
612f2f7 This commit should not be squashed
d84b05d This commit should be squashed
ac60234 Yet another commit
36d15de Rebase from here
17692d1 Did some more stuff
e647334 Another Commit
2e30df6 Initial commit
> git rebase -i 36d15de
At this point your editor of choice pops up where you can describe what you want to do with the commits. Git provides help in the comments. If you leave it as is then nothing will happen because every commit will be kept and their order will be the same as they were before the rebase. In this example we apply the following commands:
pick ac60234 Yet another commit
squash d84b05d This commit should be squashed
pick 612f2f7 This commit should not be squashed
# Rebase 36d15de..612f2f7 onto 36d15de (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
# 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
Git log after writing commit message
> git log --oneline
77393eb This commit should not be squashed
e090a8c Yet another commit
36d15de Rebase from here
17692d1 Did some more stuff
e647334 Another Commit
2e30df6 Initial commit