0
0
GitHow-ToBeginner · 3 min read

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 last N commits.
  • 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~3
💻

Example

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 N in HEAD~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

CommandDescription
git rebase -i HEAD~NStart interactive rebase for last N commits
pickUse the commit as is
rewordChange the commit message only
editPause to amend the commit
squashCombine commit with previous one
fixupLike squash but discard this commit's message
execRun a shell command
# linesComments 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.