How to Reorder Commits Using Git Rebase Easily
Use
git rebase -i HEAD~N to open an interactive editor where you can reorder commits by changing their order in the list. Save and close the editor to apply the new commit order.Syntax
The basic syntax to reorder commits is:
git rebase -i HEAD~N: Starts an interactive rebase for the lastNcommits.- In the editor, you see a list of commits from oldest at the top to newest at the bottom.
- Change the order of the commits by moving the lines up or down.
- Save and close the editor to apply the new order.
bash
git rebase -i HEAD~3Example
This example shows how to reorder the last 3 commits. The interactive editor opens with commits listed. You move the second commit to the top to change the order.
bash
git rebase -i HEAD~3 # Editor opens with: # pick a1b2c3d Commit message 1 # pick d4e5f6g Commit message 2 # pick h7i8j9k Commit message 3 # Change to: # pick d4e5f6g Commit message 2 # pick a1b2c3d Commit message 1 # pick h7i8j9k Commit message 3 # Save and close the editor
Output
Successfully rebased and updated refs/heads/main.
Common Pitfalls
Common mistakes when reordering commits include:
- Choosing the wrong number
NinHEAD~N, which may exclude commits you want to reorder. - Editing commit lines incorrectly, such as deleting lines or changing commands other than
pick. - Conflicts during rebase that need manual resolution before continuing.
- Reordering commits that have already been pushed to shared branches, which can cause problems for others.
Always make sure to backup or work on a branch before rebasing.
bash
git rebase -i HEAD~2 # Wrong: deleting a commit line accidentally # pick a1b2c3d Commit 1 # (deleted line for Commit 2) # Right: reorder without deleting lines # pick d4e5f6g Commit 2 # pick a1b2c3d Commit 1
Quick Reference
| Command | Description |
|---|---|
| git rebase -i HEAD~N | Start interactive rebase for last N commits |
| pick | Use the commit as is |
| reword | Change the commit message only |
| edit | Pause to amend the commit |
| squash | Combine commit with previous one |
| fixup | Like squash but discard this commit's message |
| exec | Run a shell command |
| # lines | Comments ignored by Git |
Key Takeaways
Use
git rebase -i HEAD~N to reorder the last N commits interactively.Move commit lines in the editor to change their order, then save and close.
Avoid deleting commit lines unless you want to remove commits.
Resolve any conflicts during rebase before continuing.
Do not reorder commits already pushed to shared branches without coordination.