Useful Git – Safely Using Stash

Stash Scenario

You’re working on a branch; halfway through making some changes. Then a PM tells you they need the last stable build from that branch ASAP.

You don’t really want to commit your current changes, then checkout a previous commit. The changes you’ve made atm aren’t really ready to be committed …

Stash is useful in this scenario, where you need to temporarily stash your changes.

Use ‘git stash save’ to stash your current working changes.

But play carefully…

This will place your working branch back to its last stable commit (the HEAD commit), allowing you to make a build for Mr PM. When you’re done, use ‘git stash list’ to view all stashes you’ve made, then ‘git stash apply stash@{[stash number here]}’ to re-apply those working changes you stashed earlier.

This way you don’t clutter the repository with half-written working changes; Mr PM doesn’t get a broken build and everyone can head out for rum earlier *happy dance*

Stash Gotchas

Stash is not a commit. Do I need to repeat that? STASH IS NOT A COMMIT! If you stash and then make changes to some files, then apply the stash, you’ll blow away any changes you make since stashing. Hence the ‘play carefully’ :-)

So rule #1 with stashing: DO NOT MAKE CHANGES TO THE HEAD IF YOU’VE STASHED (or you can expect to get beaten with git’s wooden-spoon-of-pain when conflicts arise).

Stash Shortcuts

Stash is a stack. So everytime you ‘git stash save’, Git adds your latest stash to the top of the stack.

With that in mind, you can shortcut your usage of stash commands if you need to quickly stash something…

$ git stash save (stashes your changes)
(now you can publish whatever you need from the last commit)
$ git stash pop (pops your last stash, putting you right back to where you were before stashing)

NOTE: This will pop your last stash, keeping your stash list clean. If you don’t want to pop your last stash (because you’re afraid of losing your stash), you can use ‘git stash apply’, which will apply the top stash, while leaving the stash in the stack.

Stash Beginner Advice:

Play first. Don’t use anything in Git unless you understand the consequences …play in test repositories, or “you’re gunna have a bad time”.

badTime