Tagging Stashes in Git

On many of the projects I develop, I often need to temporarily apply a particular set of changes to my working directory. For example: I may wish to apply some settings in order to run a command or perform a test.

Git’s stash feature makes this easy. First make the changes you will need to apply again. Then run git stash.

When you want to apply your stash in the future, you can retrieve your list of stashes via git stash list:

$ git stash list
stash@{0}: WIP on master: 531b57e small bug fix
stash@{1}: WIP on master: a5f035f updates
stash@{2}: WIP on master: 7bd979b copy fix

and apply it like so:

$ git stash apply stash@{1}

When you are finished with the changes, you can reset your working directory. Later, when needed, you can reapply them using the stash apply command shown above.

There are a few shortcoming with this method however:

  1. stash@{1} isn’t memorable
  2. it isn’t easy to type
  3. its number scheme is relative, e.g. if you pop the top stash, the stash@{1} reference becomes stash@{0}

And unfortunately, in case you were wondering, we can’t use the message we gave the stash (if we provided one) as a reference (because it isn’t one), so what can we do?

The solution is easy. Since Git stores stashes as commits1, we are free to tag them like any other commit.

Continuing with the example above:

$ git tag mysettings stash@{1}

Now, reapplying the changes is easy, memorable, and closer to being foolproof:

$ git stash apply mysettings

  1. We can easily verify this by asking Git what type our stash is: git cat-file -t stash@{1}, which returns commit