To squash multiple Git commits into a single commit, you can follow these steps:
Identify the number of commits you want to squash. For example, if you want to squash the last three commits, note down the commit hashes or their count.
Open a terminal or Git Bash and navigate to your repository's directory.
Ensure that you are on the branch where the commits exist. Use the command git branch
to see the current branch and switch to it using git checkout <branch_name>
if needed.
Start an interactive rebase session with the command git rebase -i HEAD~<commit_count>
, replacing <commit_count>
with the number of commits you want to squash. In our example, it would be git rebase -i HEAD~3
.
An editor will open with the list of commits in your chosen range. Each commit will have the word "pick" in front of it. Change the word "pick" to "squash" or "s" for all the commits except the first one. The first commit will be the one that the others will be squashed into. Save and close the editor.
Another editor will open, allowing you to modify the commit message. By default, Git will combine the commit messages of the squashed commits. Edit the commit message as desired, save, and close the editor.
Git will now squash the specified commits into one commit. If changes occurred during the rebase process, you might encounter merge conflicts. Resolve these conflicts as you would during a merge and use git rebase --continue
to proceed.
Once the rebase process finishes successfully, you will have a single commit that contains the changes from all the squashed commits.
Note: Squashing commits alters the commit history, and it is suggested to use this method only on your local branch if you haven't pushed the commits to a shared repository yet.