Undo the last commit and keep changes
Undo the last commit and keep its changes staged with git reset --soft HEAD~1, or unstaged with --mixed. The working tree is never touched by either.
The last commit was too early or has the wrong message, and the work in it must not be lost.
git init -q demo && cd demo
git config user.email [email protected]; git config user.name Demo
echo one > a.txt && git add a.txt && git commit -q -m first
echo two >> a.txt && git commit -q -am second
git reset --soft HEAD~1
git log --format=%s
git status -s
git commit -q -m "second, reworded"
git reset HEAD~1
git status -sfirst
M a.txt
Unstaged changes after reset:
M a.txt
M a.txtreset moves the current branch to another commit. With --soft that is all it does, so the index and the files stay as they were and the undone commit's changes appear as staged. The default --mixed also resets the index, so the same changes come back as unstaged edits, which the last status shows. Modes are described in git-reset.
The undone commit still exists in the reflog for a while, and git reset --soft HEAD@{1} brings it back. If the commit was already pushed, resetting then force pushing rewrites history for everyone, so use git revert for shared branches.