Delete Git commits

/ Jack Lot


The cheatsheet

Undoing your latest commit

git reset --soft HEAD~1

Rewinds your branch one commit back from HEAD, and extract that commit’s changes back into your staging area. --soft is non-destructive.

Deleting your latest commit (and discarding it’s changes)

git reset --hard HEAD~1

The same command as above, but the changes are thrown away along with everything in the working directory from that commit.

Deleting a commit further back in history

git rebase -i HEAD~x

Interactive rebase, where -i is interactive mode and HEAD~x is how many commits back to operate on; substitute x for whatever number reaches your commit.

After executing Git opens your terminal editor with those commits, each prefixed with pick. Change pick to drop on the one you want gone, then save and close.

pick 7f9d4bf Accessibility fix for frontpage bug
drop 3f8e810 Updated screenreader attributes

Backing out

git rebase --abort

Stops the interactive rebase and puts you back where you started. A conflict during a drop usually means a later commit changed a file the dropped commit introduced. When in doubt abort.

What dropping actually does

Deleting a commit doesn’t really remove it from the tree. Git simply rewinds the branch and replays forward without that particular commit’s changes. Every commit you didn’t delete is rewritten with a different reference. Avoid deleting commits on a shared branch.

Going further

Interactive rebase can do more than just drop commits: see techniques for rewriting Git history for an overview.

Interactive rebase is covered in depth in the rebase deconstructed course on LearnGit.io


TAGS: videos, git, tutorials