0
0
GitHow-ToBeginner · 3 min read

How to Use Git Rebase Interactive: Syntax and Examples

Use git rebase -i <commit> to start an interactive rebase session where you can edit, reorder, squash, or drop commits. This opens a text editor showing recent commits, letting you choose actions for each commit before applying changes.
📐

Syntax

The basic syntax for interactive rebase is:

  • git rebase -i <commit>: Starts an interactive rebase from the commit just before the one you specify.
  • <commit> can be a commit hash or a reference like HEAD~3 to rebase the last 3 commits.
  • The command opens your default text editor with a list of commits and commands you can apply.
bash
git rebase -i <commit>
💻

Example

This example shows how to squash the last two commits into one:

  1. Run git rebase -i HEAD~2 to edit the last two commits.
  2. In the editor, change the second commit's command from pick to squash.
  3. Save and close the editor to combine the commits.
bash
git rebase -i HEAD~2

# Editor opens with:
# pick e3a1b35 Fix typo in README
# pick 7ac9f12 Add usage example

# Change to:
# pick e3a1b35 Fix typo in README
# squash 7ac9f12 Add usage example

# Save and close editor

# Then edit commit message as prompted
Output
Successfully rebased and updated refs/heads/main.
⚠️

Common Pitfalls

Common mistakes when using interactive rebase include:

  • Choosing the wrong commit range, which can cause unexpected changes.
  • Not resolving conflicts properly during rebase, which pauses the process.
  • Forgetting to save and close the editor after editing commands or commit messages.
  • Rebasing commits that have already been pushed to shared repositories, which can cause problems for others.

Always make sure to communicate with your team before rewriting shared history.

bash
git rebase -i HEAD~3
# Wrong: editing commits already pushed without coordination
# Right: use interactive rebase only on local commits or coordinate with team
📊

Quick Reference

CommandDescription
pickUse the commit as is
rewordEdit the commit message only
editPause to amend the commit
squashCombine this commit with the previous one
fixupLike squash but discard this commit's message
dropRemove the commit

Key Takeaways

Use git rebase -i <commit> to start interactive rebase and edit commits.
Change commands like pick, squash, or edit in the opened editor to modify commit history.
Avoid rebasing commits already pushed to shared repositories without team coordination.
Resolve conflicts carefully during rebase to continue the process smoothly.
Save and close the editor properly to apply your changes.