October 21, 2019

How to Use Git Stash

Git at Scale
Version Control

Using the git stash command, developers can temporarily shelve changes made in the working directory. It allows them to quickly switch contexts when they are not quite ready to commit changes. And it allows them to more easily switch between branches.

Git stash is especially useful for Git newbies who can get overwhelmed with the amount of branching done in Git. But what happens when you are ready to pick the changes again?

Should you commit the unfinished changes? Copy the files somewhere else for safekeeping? Create a new branch and put the files there?

Stashing Your Work

Git stash manages your work queue with the principle last-in-first-out (LIFO) approach. You can “push” work into the stash. And “pop” it off later. It is important to note that Git will not stash new files in your working directory or files that are untracked or have been ignored.

This makes it very simple to stash your work, switch to another branch and back, and then resume your previous work. Let’s walk thorough your workflow:

Check the Status of Your Branch

Use git status on your local repository:

  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

 

Shelve Work Using Git Stash

To stash work, execute a git stash command. The 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.

 

If you were to do another git status command at this point, it would show no work in progress. You can confirm that you have added something to the stash by listing its contents with a git stash list command:

[email protected]{0}: WIP on master: 3acc7a9 Remove version history & my postal address from readme.md.

 

Recover Work Using Git Stash Pop or Git Stash Apply

When you want to recover that work, you can use either the git stash apply command or the git stash pop command.

Git Stash Pop

Popping your stash removes the changes from your stash and applies them to your working directory.

Git Stash Apply

You can also apply the changes to your working directory and keep them in your stash using the git status apply command. This is especially useful when applying stashed changes to multiple branches.

Discover Perforce Git Tools >>

 

Want to learn more? Explore Git best practices.