How to Squash Commits in Git?
Last Updated :
15 May, 2024
Maintaining a clean and organized Git history is very important for collaboration and project management. One way to streamline your commit history is by squashing commits, which combines multiple commits into a single, more coherent commit. In this article, we will see how to squash commits in Git.
Approach to Squash commits in Git
Step 1: Make an html file(index.html) to make changes and add different commits, after that initialize git in the current directory.
git init
Simply add all files using dot(.) and add your first commit.
git add .
git commit -m "first commit"
git add . files
Now create a branch to reflect changes
git branch -m "main"
git branch // to see current branch
git branch
Step 2: Now, make simple changes in index.html and add to git and commit three times.
git add .
git commit -m "commit message"
git changes
we can see all commit using following command
git log --oneline
Step 3: Start an Interactive Rebase
Once you have identified the commits, use the `git rebase -i HEAD~n` command, where n is the number of commits you want to squash. For example, if you want to squash the last 3 commits, you would use git rebase -i HEAD~3.
git rebase -i HEAD~3
it will open a Interactive Rebase editor.
Git will open an interactive rebase editor, listing the commits starting from the HEAD. Each commit will have a prefix like pick, indicating that Git will pick these commits during the rebase. In the interactive rebase editor, change the word pick to squash (or just s) for the commits you want to squash. Keep pick for the first commit you want to keep as-is, as it will be the base commit.
squash
Now save, “Esc->Ctrl+:->type wq” to save changes
Step 4: Now run below to command to make changes continue
git rebase --continue
it will open another editor, remove or make comment to second commit or third commit
vim editor
Now save file, it will return a message.
git rebase
we can see the result using `git log –oneline`
git log –oneline
Step 5: Push the Changes
Once you have squashed the commits, you may need to force-push the changes to the remote repository if the commits have already been pushed. Use git push origin <branch-name> –force to force-push the changes.