bashadvanced

Git Interactive Rebase Guide

Interactive rebase to reorder, edit, drop, and squash commits for a clean Git history.

bash
# Start interactive rebase for last 5 commits
git rebase -i HEAD~5

# Editor opens with commit list:
# pick abc1234 Add user model
# pick def5678 Add auth routes
# pick ghi9012 Fix typo in model
# pick jkl3456 Add tests
# pick mno7890 Update docs

# Available commands:
# p, pick   = use commit as-is
# r, reword = use commit but edit message
# e, edit   = pause to amend the commit
# s, squash = merge into previous commit (keep message)
# f, fixup  = merge into previous commit (discard message)
# d, drop   = remove commit entirely
# x, exec   = run a shell command

# Example: Reorder, squash fix into original, reword
# pick abc1234 Add user model
# fixup ghi9012 Fix typo in model
# pick def5678 Add auth routes
# reword jkl3456 Add tests
# pick mno7890 Update docs

# When using 'edit', Git pauses at that commit:
git commit --amend  # modify the commit
git rebase --continue  # proceed

# Run tests after each rebased commit
git rebase -i HEAD~5 --exec "npm test"

# Autosquash: auto-order fixup/squash commits
git commit --fixup abc1234
git rebase -i --autosquash HEAD~5

Use Cases

  • Crafting a clean commit history before merge
  • Fixing commit messages across multiple commits
  • Removing accidental commits from history

Tags

Related Snippets

Similar patterns you can reuse in the same workflow.