Referring to the Previous Git Commit

Authored by

On the command line shell, there is a magic symbol “-” (hyphen). When dealing with streams, it can refer to STDIN or STDOUT. When used in the context of the cd command, the - refers to the previous directory (it is the same as $OLDPWD). So you can switch between two directories by repeatedly entering cd -.

The - symbol also has special meaning in Git: it refers to the previous branch or tag you were on (any commit, really). So to switch back to the branch you were just on:

git checkout -

This also works with git-merge. To merge the previous branch into the current one:

git merge -

Say you are on the feature/awesome-thing branch. To merge this into a preview integration branch, push, and then go back to the feature branch:

git checkout preview
git merge -
git push
git checkout -

You can also use git-reflog (reference log) to look at a history of the commits you have had checked out, so git checkout - is actually equivalent to git checkout HEAD@{1}. To check out the commit-before-last, do git checkout HEAD@{2}. The Git reflog provides a great way to recover from a disaster via git reset --hard. (For the initiated, also check out pushd/popd for how you can navigate around directories with more history than just the one $OLDPWD.)

Leave a Reply

Your email address will not be published. Required fields are marked *