In Git, squashing multiple commits into a single commit is a way to simplify the commit history of a branch. This is useful when you have made several small, incremental commits that can be combined into a single, cohesive commit.
Here’s how to squash multiple commits into a single commit using git rebase:
Open your Git repository in your terminal.
Use the git log command to view the commit history of your branch. Identify the commit that you want to keep as the base commit for your squashed commit. Note the commit hash for this commit.
Use the git rebase -i command to initiate an interactive rebase:
# Initiate an interactive rebase
git rebase -i <base-commit-hash>
In this command, <base-commit-hash> is the hash of the commit that you identified in step 2.
In the interactive rebase editor that opens, locate the commits that you want to squash. Change the word "pick" to "squash" or "s" for each commit that you want to squash.
# Interactive rebase editor
pick abc123 First commit
s def456 Second commit
s ghi789 Third commit
In this example, the second and third commits will be squashed into the first commit.
Save and close the interactive rebase editor.
In the next editor that opens, modify the commit message for your squashed commit. The commit message should describe the changes that were made in all of the squashed commits.
Save and close the commit message editor.
Use the git log command to verify that the squashed commit has been created.
Push your changes to the remote repository:
# Push the squashed commit to the remote repository
git push --force
In this command, the –force option is necessary because you have rewritten the Git history of your branch.
In summary, squashing multiple commits into a single commit using git rebase is a way to simplify the commit history of a branch. This can be done using an interactive rebase, where you specify the commits that you want to squash and modify the commit message for the squashed commit. After squashing the commits, you should verify the changes using git log and then push the changes to the remote repository using git push –force.