Q20 of 40 · Git

How do you use interactive rebase to clean up your local commit history before raising a PR?

GitMidgitrebaseinteractivesquashhistorypr-workflow

Short answer

Short answer: `git rebase -i HEAD~N` opens an editor listing the last N commits. You can reorder, squash (combine), fixup (squash + discard msg), reword (edit message), edit (amend content), or drop commits — all before the branch is pushed.

Detail

Interactive rebase (git rebase -i) rewrites local commit history, giving you a chance to craft a clean, reviewable commit story before your work is shared. It's one of the most powerful Git features for professional workflows.

Commands you'll use most:

  • squash (s): fold this commit into the previous one, merging commit messages.
  • fixup (f): fold into previous but discard this commit's message — ideal for "address review comments" commits.
  • reword (r): keep the commit but rewrite the message.
  • edit (e): pause at this commit so you can amend content, then git rebase --continue.
  • drop (d): delete the commit entirely.
  • Reorder: just drag lines in the editor.

Auto-squashing: if you commit with git commit --fixup=<sha>, Git names the commit "fixup! original message". Running git rebase -i --autosquash HEAD~N then automatically sets the right fixup command for those commits, saving editor time.

Safety: interactive rebase rewrites SHAs — only use it on commits not yet pushed, or on your own feature branch before others have based work on it.

// EXAMPLE

# Interactively rebase the last 4 commits
git rebase -i HEAD~4

# Editor opens with something like:
# pick a1b2c3 Add OrderApiTest skeleton
# pick b2c3d4 WIP: half-done assertions
# pick c3d4e5 Fix typo in test name
# pick d4e5f6 Address review comments

# Change to:
# pick a1b2c3 Add OrderApiTest skeleton
# squash b2c3d4 WIP: half-done assertions
# fixup c3d4e5 Fix typo in test name
# fixup d4e5f6 Address review comments
# Result: 1 clean commit with the message you edit in the next prompt

# Auto-squash workflow
git commit --fixup=a1b2c3        # creates "fixup! Add OrderApiTest skeleton"
git rebase -i --autosquash HEAD~5 # Git places fixup lines automatically

# Abort if anything goes wrong
git rebase --abort

# After a successful rebase, force-push your feature branch
git push --force-with-lease origin feature/order-api-tests

// WHAT INTERVIEWERS LOOK FOR

Knowing squash vs fixup (message handling). The --autosquash/--fixup workflow for seamless squashing. The habit of cleaning history before PR. Knowing to --abort when lost.

// COMMON PITFALL

Rebasing onto a branch others are working from, causing them to have diverged histories. Interactive rebase is for your own local commits only.