How to stash in Git

Stashing in Git is a very useful technique that eases daily work with code. Many a time, you are in the middle of writing or changing some code when you might be required to quickly checkout a different branch. For example, another team member wants you to quickly run a test in a different branch or fix a bug appearing in a different branch. It is pretty easy to clone a new repository to do these things if the repository is small and building files is quick. If your repository or build setup is large, complicated or time consuming, then stashing is a great addition to your workflow.

Stashing just saves all your staged or unstaged files that are changed and saves them up in your local repository. The stashed commits are actually stored locally in a reflog for a branch named stash. So, the git stash commands are just simple wrappers over standard git commands.

The command to stash up all your changed files and have a clean slate:

$ git stash

By default this stash commit is saved with a generic commit message that includes the branch, the commit hash and the log of the commit upon which the stash was created.

It is very easy to forget what your changes your stash contained. So, I like to stash with my own commit message:

$ git stash save "WIP on enabling write to disk"

You can stash many times in a local repository. The stashes are saved in a LIFO stack. You can list and view all the stashes in the stack:

$ git stash list

You can see that this is just showing the items from the stash reflog:

$ git reflog stash

To unstash and apply the top-most item in the stack:

$ git stash apply

Since the top-most stash is applied, the above command is the same as:

$ git stash apply stash@{0}

To unstash a different item from the stack:

$ git stash apply stash@{99}

To checkout a particular file from a particular stash:

$ git checkout stash@{13} -- foobar/joe.cpp

That is all there is to it! This is one of the easier and straightforward commands in Git 🙂

Tried with: Git 2.8.3

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.