How to squash multiple commits into one in Git

Arif Billah Babu

         

  git



Image not found!!

To squash multiple commits into one in Git, you can use the interactive rebase feature. Here's a step-by-step guide:

  1. Open Terminal or Command Prompt: Open a terminal or command prompt window in your Git repository.

  2. Ensure you are on the branch where you want to squash commits: Make sure you are on the branch where you want to squash the commits.

    bash
    git checkout <your-branch-name>
  3. Start Interactive Rebase: Run the following command to start an interactive rebase:

    bash
    git rebase -i HEAD~n

    Replace n with the number of commits you want to squash. For example, if you want to squash the last 3 commits, use git rebase -i HEAD~3.

  4. An Editor will open: Git will open an interactive rebase file in your default text editor. It will look something like this:

    bash
    pick abc123 Commit message 1 pick def456 Commit message 2 pick ghi789 Commit message 3

    Change pick to squash (or just s for short) for the commits you want to squash. For example:

    bash
    pick abc123 Commit message 1 squash def456 Commit message 2 squash ghi789 Commit message 3

    Save and close the file.

  5. Edit the Commit Message: Another editor will open for you to edit the commit message. You can keep the existing messages or combine them into a new one. Save and close the file.

  6. Finish the Rebase: Finish the rebase with the following command:

    bash
    git rebase --continue
  7. Force Push: Since you have rewritten the commit history, you'll need to force push the changes to the remote repository. Use the following command:

    bash
    git push origin <your-branch-name> --force

    Note: Be cautious when force pushing, especially if others are collaborating on the same branch, as it can disrupt their work. Only force push if you are sure it won't cause issues for your collaborators.

That's it! You've successfully squashed multiple commits into one.