0
0
GitHow-ToBeginner · 3 min read

How to Edit a Commit Using Git Rebase - Step by Step Guide

Use git rebase -i HEAD~n to open an interactive list of the last n commits. Change pick to edit for the commit you want to modify, then amend the commit with git commit --amend and continue the rebase with git rebase --continue.
📐

Syntax

The main command to edit commits is git rebase -i HEAD~n, where n is the number of commits back you want to edit. This opens an editor showing recent commits. Change pick to edit on the commit you want to modify. After saving, Git pauses the rebase at that commit so you can amend it.

Use git commit --amend to change the commit message or content. Then run git rebase --continue to finish the rebase process.

bash
git rebase -i HEAD~n
# In editor, change 'pick' to 'edit' for the commit to modify
# Save and exit editor
# Git stops at the chosen commit
# Make changes or edit message

git commit --amend

# Continue rebase

git rebase --continue
💻

Example

This example edits the second last commit message. It shows how to start the interactive rebase, edit the commit, and finish the process.

bash
git rebase -i HEAD~2
# Editor opens with two commits:
# pick abc123 Fix typo in README
# pick def456 Add new feature

# Change to:
# pick abc123 Fix typo in README
# edit def456 Add new feature

# Save and exit

# Git stops at commit def456

# Change commit message:
git commit --amend -m "Add new feature with improvements"

# Continue rebase:
git rebase --continue
Output
Successfully rebased and updated refs/heads/main.
⚠️

Common Pitfalls

  • Not specifying the correct number of commits with HEAD~n can cause you to miss the commit you want to edit.
  • Forgetting to run git rebase --continue after amending will leave the rebase unfinished.
  • Editing commits that have been pushed to shared branches can cause conflicts for others.
  • Not saving changes in the editor when changing pick to edit will cancel the rebase.
bash
## Wrong way: Forgetting to continue rebase

git rebase -i HEAD~1
# change pick to edit
# save and exit

git commit --amend -m "Updated message"
# Forgot to run:
# git rebase --continue

## Right way:
git rebase --continue
📊

Quick Reference

CommandPurpose
git rebase -i HEAD~nStart interactive rebase for last n commits
Change 'pick' to 'edit'Mark commit to be edited
git commit --amendModify commit message or content
git rebase --continueResume and finish rebase

Key Takeaways

Use 'git rebase -i HEAD~n' to start editing recent commits interactively.
Change 'pick' to 'edit' for the commit you want to modify.
Amend the commit with 'git commit --amend' to change message or content.
Always run 'git rebase --continue' to complete the rebase process.
Avoid editing commits already pushed to shared branches to prevent conflicts.