I have a very messy git history. I want to squash a bunch of older commits (not including the last one).
I know how to squash my last n
commits. But this is different. Here I have commits consecutively n1
to n2
which I want to squash into one, while after n2
I have a history of commits that I want to preserve up to the last one.
So, if my current history looks like this:
---- n1 --- n2 -------- m
I want to squash n1
to n2
so it ends up looking like this:
---- n1n2 -------- m
where n1n2
is a single commit containing the squashed contents from n1
to n2
.
How should I do this? What are the consequences on the history from n2
to m
?
That is, will the hash of every commit from n2
to m
change as a consequence of what I want to do?
To "squash" in Git means to combine multiple commits into one. You can do this at any point in time (by using Git's "Interactive Rebase" feature), though it is most often done when merging branches.
Git Squash CommitsSquashing is a way to rewrite your commit history; this action helps to clean up and simplify your commit history before sharing your work with team members. Squashing a commit in Git means that you are taking the changes from one commit and adding them to the Parent Commit.
You can do an interactive rebase, per the docs and this blog post.
Start an interactive rebase:
git rebase -i HEAD~n
(where n
is how far do you want to go back in history)
Your default editor will open. At the top, a list of your latest n
commits will be displayed, in reverse order. Eg:
pick a5f4a0d commit-1
pick 19aab46 commit-2
pick 1733ea4 commit-3
pick 827a099 commit-4
pick 10c3f38 commit-5
pick d32d526 commit-6
Specify squash
(or the shortcut s
) for all commits you want to squash. E.g.:
pick a5f4a0d commit-1
pick 19aab46 commit-2
squash 1733ea4 commit-3
squash 827a099 commit-4
pick 10c3f38 commit-5
pick d32d526 commit-6
Git applies both that change and the change directly before it and makes you merge the commit messages together.
Save and exit.
Git will apply all changes and will open again your editor to merge the three commit messages. You can modify your commit messages or leave it as it is (if so, the commit messages of all commits will be concatenated).
You're done! The commits you selected will all be squashed with the previous one.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With