git-stash is a recent addition to git. It was introduced in version 1.5.3.

The best way to describe what git-stash is useful for is describing a scenario.

Pretend you’re in the middle of working on feature A. You’ve created a branch and have a few patches in it. In the middle of working on your current patch, you find a pretty glaring bug that existed before you started. How will you fix it?

You could fix it and commit just it using something like git-add--interactive or just git-add (if the fix is in a different file), but then your bugfix commit will be in the middle of your feature branch. This is not good.

You could git-checkout your main (usually master) branch and try to work around your working copy changes. In this case, you’re very likely to have merge problems and lose some of your in-progress changes. This is not good.

You could create a temporary commit (by putting TEMPORARY somewhere in the commit message, so you don’t forget), git-checkout your main branch, commit the bug fix, git-checkout the feature A branch, and git-reset HEAD^ the commit. More likely you’ll do every step except the last one and you’ll have a temporary commit in your history that doesn’t make any sense to anyone but yourself. This is not good.

Instead you can use git-stash to keep track of your working copy changes and convert the working copy back to an unmodified version of your feature branch. Then git-checkout won’t have any problems checking out your main branch, you’ll have no problems committing your bugfix, and when you git-checkout back to your feature branch you can just apply the stash onto your working copy. This way you’ll never accidentally commit unfinished changes and you won’t have to worry about losing uncommited changes.

git-stash has a few main options:

  • git-stash list
  • git-stash show [stash]
  • git-stash apply [stash]
  • git-stash [save]
  • git-stash clear

git-stash list shows you all the stashes you have… well… stashed.

git-stash show shows you a specific stash (or all of them if you don’t specify which one). git-stash show works really well when you pass it -p (ie. git-stash show -p stash@{1}) because it will show you the entire diff contained in that stash.

git-stash apply applys a stash to your working copy.

git-stash (or git-stash save <message>) saves your changes in a stash. By default git-stash names the stash after the commit it is on top of. By specifying a message you can make it easier to discern your stashes later.

git-stash clear deletes all stashes. Because stashes are stored in the git object database, they have to follow the same restrictions as blobs, trees, and commits. This means that git-stash clear is not able to delete a single stash, it can only delete the entire stash list.

Just remember, when you don’t want to forget changes that you don’t want to commit, use the stash!

References:

Advertisements