Squash Commits via the git rebase Command
Learn to squash multiple commits using git rebase.
We'll cover the following
Add files and commits
In the terminal provided at the end of the lesson, we add some files and make changes to them. We create two files, file1.txt
and file2.txt
. Two branches, main
and feature_a
, are also created. We add four lines to file2.txt
, one after the other. We have already run these commands in the terminal at the end of the lesson.
$ git checkout -b main
$ touch file1.txt
$ git add file1.txt
$ git commit -m "creation of file1"
$ git checkout -b feature_a
$ 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"
$ echo "line 2" >> file2.txt
$ git add file2.txt
$ git commit -m "line 2 file 2"
$ echo "line 3" >> file2.txt
$ git add file2.txt
$ git commit -m "line 3 file 2"
$ git status
Now, run this command in the terminal below:
$ git log --oneline --graph --decorate --all
When we run the git log
command, we see the commit history of the creation of files and changes in it:
* cbae73c (HEAD -> feature_a) line 3 file 2
* 3cc7357 line 2 file 2
* 8c92700 line 1 file 2
* 1f8f7c1 creation of file2
* 86f6ad0 (main) creation of file1
Use git rebase
interactively
We can modify the history of commits by using interactive git rebase
, which is git rebase -i main
.
Run the git rebase -i main
command. We see the default editor opens with the content below.
This is a critical step. The commits that are rearranged are listed in the file. By default, they have pick
status. We can choose how these commits are rearranged during the rebase, including changing the commit messages or even deleting the commits.
$ git rebase -i main
Get hands-on with 1400+ tech skills courses.