Marius Schulz
Marius Schulz
Front End Engineer

How to Squash the First Two Commits in a Git Repository

I recently needed to squash the first two commits in one of my Git repositories. As usual, I ran the git rebase -i command to do an interactive rebase, but I noticed that the root commit didn't appear in the list of commits.

Here's what my Git history looked like:

$ git log --graph --oneline
* fe2c946 (HEAD -> main) More changes
* 2702f8b Small tweaks
* ffb98dd Initial commit

When I ran git rebase -i ffb98dd, this was the output I got (omitted for brevity):

pick 2702f8b Small tweaks
pick fe2c946 More changes

# Rebase ffb98dd..fe2c946 onto ffb98dd (2 commands)
# ...

As you can see, the second commmit 2702f8b and the third commit fe2c946 were listed, but the initial commit ffb98dd wasn't. So how do you squash the second commit into the root commit if the root commit isn't listed?

The solution for this problem was introduced in Git 1.17.12. We can now specify the --root flag for the rebase command to rebase all reachable commits up to the root:

$ git rebase -i --root

This allows us to rewrite the Git history down to the root commit. Now, the output includes the root commit ffb98dd in the first line:

pick ffb98dd Initial commit
pick 2702f8b Small tweaks
pick fe2c946 More changes

# Rebase fe2c946 onto 6fafbe0 (3 commands)
# ...

We can use the squash command in the second line to combine ffb98dd and 2702f8b into a single commit:

pick ffb98dd Initial commit
squash 2702f8b Small tweaks
pick fe2c946 More changes

# Rebase fe2c946 onto 6fafbe0 (3 commands)
# ...

Now, we need to choose a message for the new combined commit. I kept "Initial commit" since it's still an accurate description. Once the command completes, the Git history looks like this:

* bfd9495 (HEAD -> main) More changes
* 34901ec Initial commit

And there we go! The changes made in the "Small tweaks" commit 2702f8b have been folded into our initial commit. Using the --root option with the rebase command, we were able to squash the first two commits into a single one.

Buy Me a Coffee