Squash commits in Git
- In Git, squashing commits means combining multiple commits into a single one. For example, if we are working on a separate feature branch, there may be a large number of commits depending on the duration of work. Once it is completed, we need to merge it to the main branch. If we decide to squash before merging, all those individual commits from the feature branch will be combined into a single commit. Hence the main commit history shows a single commit.
Squashing is used to condense a large number of commits into small meaningful commits so that we can make the git history clearer.
How to squash commits?
- Let us check the commit history using the below command;
$git log –oneline
- Assume we want to squash the last 4 commits. We can do so by starting an Interactive Rebase session.
$git rebase -i HEAD~N
where N is the number of commits you want to join, starting from the most recent one.
- Here, we need to squash last 4 commits so N=4
$git rebase -i HEAD~4
- An editor window appears showing the list of commits you want to merge. They are displayed in a reverse order, where the older commit is on top.
- You need to mark one or more lines as “squash” or “s“, they will be combined with the one above.
- Save the file.
- We have combined all 4 commits in to first commit in the list. We need to give a name for the squashed commit. The editor pops again with a default message, made of the names of all the commits squashed. Save the file.
- At this point, you can delete all the messages you don’t want to be included in the final commit version.
- After entering the commit message for the new combining commit, the three old commits have been squashed into one. The git log is as follows;
- Note that the commit hash has also changed. git rebase will always create a new commit with respective changes.
- In the case of git rebase -i HEAD~N command, we need to know the exact number of commits by counting them one by one. There is another way for squashing commits.
- Make sure you have checked out the correct branch before performing the Git squash operation.
$git rebase -i (commit hash)
where [commit-hash] is the hash of the oldest commit from where you have to start squashing.
DevOps Gurukul is one of the best training academies which provides Complete RedHat Linux Training Course and Best online linux course in Kerala.