Git Undo

Git doesn't make mistakes, you do. Here are some common mishaps and how to recover.

Wrongful Commit

A number of ways you can modify the last commit

# change last commit message
git commit --amend

# undo last commit but leave files staged
git reset --soft HEAD~1

# undo to specific commit
git reflog
git reset HEAD@{1}

# undo last local commit, not pushed yet
git reset --hard HEAD~1

# undo last public commit, already pushed
git reflog
git revert HEAD@{1}

Cleared Stash

You just ran `git stash clear` but need your last stash

# locate your stash SHA1
gitk --all $( git fsck --no-reflog | awk '/dangling commit/ {print $3}' )
git stash apply <sha1>

Rebase

You want to undo a rebase? Use the reflog

# reset your HEAD to before the rebase
git reflog
git reset HEAD@{1}

Deleted Branch

You've just deleted a branch, by mistake!

# use reflog to find the SHA1 at the tip of your deleted branch
git reflog
# recreate the branch you lost
git checkout -b <branch> <sha>

Staged Files

Unstage a file to be committed

# to unstage file but keep the changes
git reset HEAD <file>
# to unstage file and discard changes
git checkout HEAD <file>
comments powered by Disqus