More Git-Stash Tricks

Previously I wrote about testing code with git-stash. Now I want to share some other tricks. Stashing can do more than simply hide your unstaged changes, and I’ll show you how.

Note: You should have a basic understanding of Git terms like the ‘index’ and ‘reflog’.

Accessing Stashes

The command git stash show will list all of your stashes. Each will have a name (i.e. a ‘ref’) next to it that will look like stash@{0}, stash@{1]}, and so on. There will also be hash numbers next to them. You can use this hash to retreive a stash even if you seemingly got rid of it via git stash pop. Consider this output:

$ git stash show
stash@{0}: On feature/foo: 8a40ce... Trying to fix a bug
stash@{1}: On feature/foo: df119c... Testing
stash@{2}: On feature/bar: 714cc2... Possible bug fix

Normally you pop the latest stash, i.e. stash@{0}. But since we can see the SHA-1 hashes of each stash we can use those to select specific ones. Let’s say we want the last one, stash@{2} Here are some options:

  1. We can explicitly provide the hash, i.e. git stash pop 714cc2. This will remove the stash from the list.

  2. We could use git stash apply 714cc2. It does the exact same thing except it does not remove the stash.

  3. We could cherry-pick it to our current branch via git cherry-pick 714cc2.

  4. Or we could create a new branch that begins from the point where we originally made the stash, e.g. git stash branch more/bar/work 714cc2.

So hopefully you can see that we can use the stash as more than a stack.

Dropping Stashes

If we have the SHA-1 for a stash and no longer need it then we can run git stash drop 714cc2, or whatever is the hash number. We could probably also write git stash drop stash@{2} but I have never tried this myself. For those times when we want to get rid of everything we have the command git stash clear. It wipes out every stash.

Bringing Stashes Back From the Grave

If you accidentally get rid of a stash then you can still get it back, so long as Git has run its garbage collection or you haven’t run git gc yourself. This shell command is fairly esoteric, so forgive me for not explaining the details. I’ll come back to it another day, especially to explain git fsck. Here it is:

$ git fsck --unreachable |
    grep commit  |
    cut -d\  -f3 |
    xargs git log --merges --no-walk --grep=WIP

Kind of a mouthful, but like I said, I’ll come back to it another day. In the mean time I hope you find some of these stashing commands useful and learn to look at it as more than just a first-in-first-out stack.


Add Your Thoughts

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s