Hone

Lessons · Git · undoing a commit, keeping the work

Undoing a commit and keeping the work

git reset --soft HEAD~1 moves the branch back one commit and leaves everything staged, exactly as it was the moment before you typed commit.

Hone is a place to practise programming. This is one of its lessons, written out in full and free to read without an account.

What it is for

Committing too early, with the wrong message, or with a file you meant to leave out -- all of them are this, and none of them needs the work to be retyped.

How to think about it

Soft while the commit is yours alone. Once it is pushed, the answer is revert instead, because moving the branch back rewrites what other people have.

Worked example

git log --oneline
Two commits, and the second one should not exist yet.
git reset --soft HEAD~1
The branch moves back. Nothing else does.
git log --oneline
One commit.
git status --short
M in the left column: the work is staged, ready to commit again.
git commit -qm 'what it should have said'
And now it says what you meant.

Your turn

Undo the last commit but keep everything staged.

git reset  HEAD~1

The trap

Doing this to a commit you have pushed. Your repository is fine; everybody else's now disagrees with the remote about what the branch is.

Practise undoing a commit, keeping the work on HoneA question on it now, a coding challenge where there is one, and it is remembered for review. Free, no email needed.