Group Commits With the git reset Command

Learn to group multiple commits into one commit by using git reset.

The git reset command

The git reset command removes the commits and puts the changes in either the staged area (with the --soft flag) or in the unstaged area (without the --soft flag).

Group multiple commits

If we reset multiple commits, the changes in these commits are grouped. We can then commit again including all these changes in one commit. In this way, we can group multiple commits into one commit.

Usefulness of grouping commits

This technique is useful when we have multiple commits that serve a single purpose. This may happen when we create a commit and then find minor issues to fix until we deliver the implementation. We may need additional commits to fix tiny mistakes.

Before we deliver and push those commits, it makes sense to group them into one commit.

For example, we’ve run the following commands in the terminal below:

$ mkdir SampleProject
$ cd SampleProject
$ git init
$ touch file1.txt
$ git add file1.txt
$ git commit -m "creation of file1"
$ touch file2.txt
$ git add file2.txt
$ git commit -m "creation of file2"
$ echo "line 1" >>  file2.txt
$ git add file2.txt
$ git commit -m "line 1 file 2"
$ git commit -m "creation of file2"
$ echo "line 2" >>  file2.txt
$ git add file2.txt
$ git commit -m "line 2 file 2"
$ git commit -m "creation of file2"
$ echo "line 3" >>  file2.txt
$ git add file2.txt
$ git commit -m "line 3 file 2"
$ git commit -m "creation of file2"
$ echo "line 4" >>  file2.txt
$ git add file2.txt
$ git commit -m "line 4 file 2"

We create a directory named SampleProject. Inside this directory, we initialize Git, create two files (file1.txt and file2.txt), and commit them. After initial commits, we make changes to the file file2.txt and then commit it again.

Now, run the following commands:

$ git status
$ git log --oneline --graph --decorate --all

We get the following output (the commit IDs can be different):

* 881ea82 (HEAD -> master) line 4 file 2
* fed32df line 3 file 2
* 9956807 line 2 file 2
* 617ecf3 line 1 file 2
* 2626bb9 creation of file2
* 2c02725 creation of file1

Get hands-on with 1200+ tech skills courses.