The git rebase
command offers powerful options in its --interactive
mode, commonly abbreviated as -i
. One of the most popular features is the ability to squash commits, which merges smaller commits into larger ones. This can be useful when organizing your changes or preparing to finalize your work. Let’s explore how to do this effortlessly.
Before we begin, a word of caution: Only squash commits that haven’t been pushed to an external repository. Rewriting shared history can lead to conflicts and potential data loss.
Step-by-Step Guide to Squashing Commits
Imagine you’ve made several small commits and now want to combine them into one larger commit. Here’s how you can achieve this through interactive rebasing:
- Start an interactive rebase session by specifying the number of commits you want to rebase. For example, to squash the last four commits, run:sh
$ git rebase -i HEAD~4
Git opens an editor with a list of the selected commits and their respective messages. It also provides instructions on how to proceed.
Change the pick
command to squash
for all but the first commit. This tells Git to combine these commits into the first one. For example:
pick 01d1124 Adding license squash 6340aaa Moving license into its own file squash ebfd367 Jekyll has become self-aware. squash 30e0ccb Changed the tagline in the binary, too.
- Save and close the editor. Git will prompt you to enter a new commit message for the squashed commits.
- Edit the commit message as needed, combining information from the original messages.
- Save and close the editor again to complete the rebase process.
Resolving Conflicts and Recovering Lost Commits
If conflicts occur during the rebase, resolve them as usual by editing the conflicting files, staging the changes, and continuing the rebase with git rebase --continue
.
If you accidentally lose a commit during the rebase, use git reflog
to retrieve it from Git’s history.
Conclusion
Squashing commits with rebase offers a convenient way to organize your commit history and present your changes more effectively. However, exercise caution when squashing commits, especially in shared repositories.
By mastering the interactive rebase feature, you can streamline your workflow and maintain a cleaner commit history. Experiment with other uses of git rebase -i
and share your experiences with the community.
For more in-depth guidance on interactive rebasing, consider exploring resources such as GitCasts’ video tutorials.