Skip to content

Instantly share code, notes, and snippets.

@lioncash
Last active September 1, 2023 07:14
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lioncash/fbf57f875575d3e13484 to your computer and use it in GitHub Desktop.
Save lioncash/fbf57f875575d3e13484 to your computer and use it in GitHub Desktop.
Basic guide for squashing commits using interactive rebase in the CLI

1. Find the commit hash before the commit you want to squash

Say you make three commits, each one labeled "First commit", "Second commit", and "Third commit" respectively. Now, you want to squash the third commit into the second commit. You'll want to get the hash for the commit behind the commit we want to squash things into, so the commit that we're squashing things into shows up in the staging area.

So, type git log and hit enter and you'll be presented with the following screen:

You'll want to use the Git hash that belongs to the commit labeled "First commit", since it's the commit behind the one you want to squash commits into. So, the Git hash to use for this case is 61379850f559b38df6e800866eff6a7bb49b874d.

Alternatively, if you remember the number of commits you made that you want to squash, you can just run git rebase -i HEAD~n, where n is the number of commits you made.

2. Run interactive rebase

Now that you have the Git hash, run git rebase -i 61379850f559b38df6e800866eff6a7bb49b874d. You'll be presented with the following screen:

3. Select the commits to squash

As you'll see, s or squash is the command to meld commits into previous ones. So, you just have to change the third commit from pick over to one of those. If your git CLI editor uses Vim and you aren't familiar with it, press i to enter insert mode so you can edit text. Change the text to look like the following:

Now, press escape and then type :x to save and exit.

4. Modify the commit message for the commit created from the squashed commits

Now, since you're merging two commits into one another, Git will present you with the option to modify the commit message, like so:

Modify the commit message to whatever you want, then type :x to save and exit one last time. If no conflicts occur, Git should successfully squash the commits. Now, if you run git log again, you should only see two commits: the first one, and the one created from the squashing.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment