Amending a Commit Message
Amending and Fixing an Incorrect Commit Message
After this page you can replace the last commit’s message, and you know when that is safe.
The last commit only
cd ~/desk/desk-api
git log -1 --format='%s'
git commit --amend -m "docs: document GET /ping in README"
git log -1 --format='%h %s'--amend writes a new commit object with the same tree and parent (unless you also staged files) and slides the branch name to it. The old hash disappears from git log. It is still in git reflog for about 30 days (chapter 17).
before after
A ← B ← C main A ← B ← C' main
│ ╲
└── message "stuff" C still in reflog
Keep the old message and only restage files:
git add src/ping.py
git commit --amend --no-editOpen the editor with the old message loaded:
git commit --amendcore.editor (chapter 2) is what opens. On Linux with nvim, you edit, save, quit, and Git takes the buffer.
When this is safe
Safe when all of these hold:
- it is
HEAD(the latest commit on this branch) - you have not pushed, or you are the only clone
- nobody else based work on the old hash
After a push, amending means a force-push (chapter 11). On main shared with a team, prefer a new commit: git commit -m "docs: fix typo in README".
Older than HEAD
--amend cannot retitle commit HEAD~3 by itself. Interactive rebase can (chapter 9, reword). For now, live with old subjects or wait for rebase.
Recover if you amended by mistake
git reflog
git reset --soft HEAD@{1}--soft moves HEAD back and leaves the index and working tree as they are. Chapter 7 is reset in full. The hash you just left is in the reflog (chapter 17). This one-liner is enough if you just amended and panicked.
Identity in an amended commit
Amend rewrites the committer date by default. The author stays. To keep both timestamps:
git commit --amend --no-edit --date="$(git log -1 --format=%aD)"Rarely needed. Know that git log after an amend shows “now” as the committer time.