How can you squash commits interactively using rebase?
Posted by CarolTh
Last Updated: July 10, 2024
To squash commits interactively using Git's rebase functionality, you can follow these steps: 1. Open the terminal and navigate to your repository. 2. Determine the number of commits to squash. You need to know how many commits from your current branch you want to squash. You can view your commit history with:
git log --oneline
3. Start an interactive rebase. Use the following command, replacing N with the number of commits you want to squash:
git rebase -i HEAD~N
For example, if you want to squash the last 3 commits, use HEAD~3. 4. Edit the rebase todo list. An editor will open showing a list of commits in the specified range. The commits will be prefixed with the word pick. It will look something like this:
pick 1234567 Commit message 1
   pick 89abcdef Commit message 2
   pick fedcba9 Commit message 3
5. Change 'pick' to 'squash' (or 's'). For the commits that you want to squash into the first one, replace pick with squash (or just s). The first commit (the one you want to keep as the main commit) should remain as pick. Here's an example of how it might look:
pick 1234567 Commit message 1
   squash 89abcdef Commit message 2
   squash fedcba9 Commit message 3
6. Save and close the editor. The editor will vary depending on your system and configuration (e.g., Vim, Nano). Make sure to save your changes and exit the editor. 7. Edit commit messages. After saving, another editor window will open, allowing you to combine and edit the commit messages for the squashed commits. You can modify the message to reflect the changes from all the commits you're squashing, or leave it as it is. 8. Complete the rebase. After you finish editing the commit message, save and close the editor. Git will then apply the changes and finish the rebase process. 9. Handle any conflicts, if necessary. If there are merge conflicts, Git will pause the rebase and prompt you