The Spaghetti Refactory Established 2015

Git stash is like a little mini save state

I’ve used this so many times and it has probably saved me all kinds of time, so I wanted to share.

Say you’ve just done a bunch of work on a new feature, modified 12 different files, and you haven’t committed anything yet. First of all:

But I know we’ve all done that. Now let’s say that you did all this on the wrong branch by accident. Sometimes git will let you switch branches without committing and take your work with you. I don’t know the hard and fast rules on how that works, and it seems to never work that way when I want it to.

If all of the work was in one file, it’d be simple enough to do some copypasta into the file on a new branch. Since we have workin a bunch of different files, that’s a no go.

Luckily, git gives us something called git stash.

Run git stash on all of your uncommitted work, and it will save it to a stash on your system. You can then shift to your new branch, and retrieve the stash by running git stash apply. Pretty cool!

Now let’s say you got yourself into a REAL mess. Let’s say that you did a bunch of work on the wrong branch, so you git stash-ed it, but you didn’t apply that stash to the correct branch. Then let’s say you got hungry and decided it was peanut butter jelly time. Then say you came back from lunch and did a bunch more work on the wrong branch.

You can git stash that work too, but when you go to apply all of your work (both stashes), it only applies the most recent. What happened to the first stash you made?

It’s still saved, but to access it, you have to run git stash list. This will show all of your stashes with the branch name where they were stashed from, and the most recent comment at the time of stashing. For example:

stash@{0}: WIP on damn_the_torpedoes: 240228e Merge pull request #384 from supremebeing7/jam_radar
stash@{1}: WIP on fix_thrusters: 7ed822 Merge pull request #383 from supremebeing7/add_lasers

To apply a particular stash, get the stash key (the stash@{x} at the beginning of the line) and run git stash apply {stash_key}. For example, if I want the work that I stashed on my fix_thrusters branch, I should run

git stash apply stash@{1}

Hopefully you get as much utility out of this as I have.