Skip to content
shellhacks.dev
Git

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.

1 min read
Summarize in AI

The last commit was too early or has the wrong message, and the work in it must not be lost.

Shell
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 -s
Text
first
M  a.txt
Unstaged changes after reset:
M	a.txt
 M a.txt

reset 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.

Taggedgit
Share

More snippets

Git

Show the current branch name

Print the current branch name with git branch --show-current, which prints nothing on a detached HEAD, where rev-parse --abbrev-ref prints the word HEAD.

1 min read
Git

Show the repository root

Print the root of the working tree with git rev-parse --show-toplevel, from any subdirectory, and cd to it in a script that must run from the top.

1 min read
Git

Check for uncommitted changes in a script

Test for uncommitted changes in a script with git diff --quiet, which exits 1 on a change. Add --cached for staged work, since untracked files never count.

1 min read

Get new posts by email

One email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.