Stashing

Author

Marie-Hélène Burle

Stashing is a way to put changes aside for some time. Changes can be reapplied later (and/or applied on other branches).

Why would you want to do that? And how?

What are Git stashes?

Having a clean working tree is necessary for many Git operations and recommended for others. If you have changes from an unfinished piece of work getting in the way, you could do an ugly commit to get rid of them. But if you care about having an organized history with meaningful commits (or if you don’t want others to see your messy drafts), stashing is a much better alternative.

Creating a stash

You can stash the changes in your modified files with:

git stash

To also include new (untracked) files, you have to use the -u flag:

git stash -u

Listing stashes

Of course, you don’t want to lose or forget about your stashes.

You can list them with:

git stash list

Stashes are also shown when you run git log (with any of its variations) with the --all flag.

Example:

git log --graph --oneline --all

Re-applying changes from a stash

To re-apply the changes (or apply them on another branch), you run:

git stash apply

If you had staged changes, you can also restore the state of the index by running instead:

git stash apply --index

If you created multiple stashes, this will apply the last one you created. If this is not what you want, you have to specify which stash you want to use with the reflog syntax:

  • stash@{0} is the last stash (so you can omit it)
  • stash@{1} is the one before it
  • stash@{2} the one before that
  • etc.

To apply the stash before last:

git stash apply stash@{1}

Deleting a stash

You delete the last (or the only) stash with:

git stash drop

Here again, if you want to delete another stash, specify it with its reflog index.

To delete the antepenultimate stash:

git stash drop stash@{2}

You can apply and delete a stash at the same time with:

git stash pop

This is convenient, but less flexible.