My blog, keeping you up-to-date on my latest news.

Stashing your work with git

What is Git Stash?

Often when you use git in collaboration, things have some changes and you want to switch branches to work on another tasks. The problem is, you don't want to do a commit of half-done work and don't want to loose what you already do.

So the anwser to this issue is the git stash command.

Start the Stashing

To demonstrate, you will go into your project and start working on a couple of files.
If you run git status, you can see your dirty state:

You can reapply the one you just stashed by using the command shown in the help output of the original stash command: git stash apply.
If you have more than one stash in your list and you want to apply one of the older stashes, you can specify it by naming it, like this: git stash apply stash@{1}.

You can see that Git re-modifies the files you uncommitted when you saved the stash.
You can save a stash on one branch, switch to another branch later, and try to reapply the changes.
You can also have modified and uncommitted files in your working directory when you apply a stash, git gives you merge conflicts if anything no longer applies cleanly.

The changes to your files were reapplied, but the file you staged before wasn't restaged.
To do that, you must run the git stash apply command with a --index option to tell the command to try to reapply the staged changes.

You can also run git stash pop to apply the stash and then immediately drop it from your stack.

Un-applying a Stash

In some use case scenarios you might want to apply stashed changes, do some work, but then un-apply those changes that originally came from the stash.
Git does not provide such a stash unapply command, but it is possible to achieve the effect by simply retrieving the patch associated with a stash and applying it in reverse:

got@GoT:$ git stash show -p stash@{0} | git apply -R

Again, if you don't specify a stash, Git assumes the most recent stash:

got@GoT:$ git stash show -p | git apply -R

If you want you can create an alias and effectively add a stash-unapply command to your git:

Creating a Branch from a Stash

If you stash some work, leave it there for a while, and continue on the branch from which you stashed the work, you may have a problem reapplying the work, because if the apply tries to modify a file that you've modified, you will get a merge conflict.
So the easiest way to test the stashed changes again, you can run git stash branch, which creates a new branch for you, checks out the commit you were on when you stashed your work, reapplies your work there, and then drops the stash if it applies successfully: