November 24, 2014

Git Beyond the Basics: Stashing Work in Progress

Git at Scale

git beyond basics

 

This is part 3 of a 6-part series on Git commands.

One of Git’s particularly useful features is stashing. The Git newbie can be overwhelmed easily with the power of light, in-place branching, particularly if his colleagues are Git experts who branch all the time.

Switching from one branch to another is simple enough, but the familiar process can easily produce a deer-in-the-headlights effect when a developer is first confronted by the question of what to do with work in progress. Should he simply commit unfinished changes? Copy the files somewhere else for safekeeping? Create a new branch and put it there?

This is exactly the type of scenario for which the Git stash feature is intended. The stash is a last-in-first-out (LIFO) queue of work in progress. You can “push” work onto the stash and “pop” it off later as you wish. This makes it very simple to stash your work, switch to another branch and back, and then resume your previous work by applying the stash.

For example, I’ve added a new file to a local Git repository. This is easily seen in the following output of the git status command:

  On branch master
  Your branch is up-to-date with 'origin/master'.

  Changes to be committed:
    (use "git reset HEAD ..." to unstage)

	  new file:   MAKEFILE

To stash this work I execute a git stash command, which provides the following output:

Saved working directory and index state WIP on master: 3acc7a9 Remove version history & my postal address from readme.md.

HEAD is now at 3acc7a9 Remove version history & my postal address from readme.md.

Another git status command at this point shows that I have no work in progress. I can confirm that I’ve added something to the stash by listing its contents with a git stash list command:

stash@{0}: WIP on master: 3acc7a9 Remove version history & my postal address from readme.md.

If I want to recover that work, I can use either the git stash apply command or the git stash pop command, the difference being that the latter removes that work from the stash in the process. I can even selectively pick and choose which entries on the stash to apply if needed.

In short, the stash is an easy place to store work for later. Those interested in more details should take a look at the Git Book documentation.