This tutorial aims to instruct you on how to squash and amend commits in Git. Squashing is a method to condense multiple commits into a single commit, and amending allows you to modify the most recent commit.
By the end of this tutorial, you will be able to:
- Understand what squashing and amending commits in Git means
- Squash multiple commits into one
- Amend a commit
Basic knowledge of Git is required. You should know how to make commits before proceeding with this tutorial.
Squashing is a Git function that allows you to turn multiple commits into one. This is especially useful when you have a lot of commits of a minor nature that clutter up your commit history.
git rebase -i HEAD~n
, replacing n with the number of commits you want to squash. This command will open an interactive rebase session.pick
with squash
or s
next to the commits you want to squash into the commit before it. The first commit should be left as pick
.git push origin branch-name --force
to push the squashed commit to the remote repository.Amending is a Git function that allows you to modify the most recent commit. This is useful if you made a mistake in your last commit.
git commit --amend
. If you don't want to change the commit message, use git commit --amend --no-edit
.--no-edit
option, an editor window will open for you to change the commit message. Save and close when you are finished.git push origin branch-name --force
to push the amended commit to the remote repository.Suppose you have a commit history of 5 commits and you want to squash the last 4 commits into the first one.
$ git rebase -i HEAD~5
This will open your text editor with something like this:
pick 01d1124 Adding feature X
pick 6340aaa Fixing bug
pick ebfd367 Updating feature
pick 30e0ccb Refactoring code
pick b073cf Updating readme
Change pick
to squash
for commits you want to squash:
pick 01d1124 Adding feature X
squash 6340aaa Fixing bug
squash ebfd367 Updating feature
squash 30e0ccb Refactoring code
squash b073cf Updating readme
Save and close your editor. A new editor window will open for you to change the commit message of the new squashed commit. After saving and closing, push the changes to the remote repository.
$ git push origin main --force
Suppose you've just made a commit and you realize you forgot to add a file, file.txt
.
$ git add file.txt
$ git commit --amend --no-edit
$ git push origin main --force
You have learned how to squash multiple commits into one and how to amend the most recent commit. These are useful skills for maintaining a clean and readable commit history.
Squash your last 3 commits into one.
Amend your last commit to include a new file, newfile.txt
.
Squash your last 5 commits and change the commit message to "5 commits squashed".
Try to make a habit of squashing and amending your commits where necessary. It's a good practice to keep your commit history clean and concise.