How to modify existing, unpushed Git commit messages?

To modify existing, unpushed Git commit messages, you can use the following methods depending on whether the commit is the latest one or an older commit in your history:

1. Modify the Latest Commit Message

Use git commit --amend to edit the message of the most recent commit:

git commit --amend
  • This opens your default text editor (e.g., Vim, Nano, or VS Code) to edit the message.
  • Save and exit the editor to update the commit message.

Example:

# Edit the latest commit message
git commit --amend -m "New commit message"

2. Modify Older Commit Messages

For commits that are not the latest, use interactive rebase to rewrite history:

# Start interactive rebase for the last N commits (replace N)
git rebase -i HEAD~N
  • Replace N with the number of commits to edit (e.g., HEAD~3 for the last 3 commits).
  • In the interactive editor:
  1. Replace pick with reword (or r) next to the commit(s) you want to edit.
  2. Save and exit the editor.
  3. For each marked commit, Git will prompt you to edit its message. Modify the message, save, and continue.
  • Complete the rebase after all edits.

Example Workflow:

# Rebase the last 3 commits
git rebase -i HEAD~3

# In the editor:
# Change "pick" to "reword" for the target commit:
pick abc1234 Original message 1
reword def5678 Original message 2  # Edit this commit's message
pick ghi9012 Original message 3

# Save and exit, then edit the message(s) as prompted.

Key Notes

  • Unpushed Commits Only: These methods are safe for commits not yet pushed to a remote.
  • Force Push After Rebasing: If commits were already pushed, use git push --force (but avoid this on shared branches).
  • Avoid Editing Public History: Never modify commits that others might have pulled.

Tips

  • Change Default Editor: Configure Git to use a preferred editor (e.g., VS Code):
  git config --global core.editor "code --wait"
  • Abort a Rebase: Cancel mid-rebase with git rebase --abort.

By following these steps, you can safely edit commit messages in your local Git history!

Leave a Reply

Your email address will not be published. Required fields are marked *