Git Stash — What, Why, and When

By Guilherme Luiz Maia Pinto
Picture of the author
Published on
Git Stash — What, Why, and When Banner

Switching branches with uncommitted work can be risky. git stash is a safe way to save your changes temporarily without committing them, so you can switch branches and come back later. This guide explains the essentials and gives you the commands you will use most often.


What is git stash?

git stash saves your local changes on a stack, without committing them. It lets you get a clean working directory quickly, then restore the changes later when you are ready.


How does it work?

  • git stash — Stashes your current changes.
  • git stash list — Shows all your stashed entries.
  • git stash apply — Reapplies the last stash without removing it from the stack.
  • git stash drop — Deletes a stash entry.
  • git stash pop — Applies and removes the last stash in one step.

Example:

# Save changes
git stash

# Switch branches safely
git checkout feature-x

# Come back and reapply
git checkout main
git stash pop

Working with multiple stash entries

Each entry is stored as stash@{n}, where n is its index. You can:

  • git stash show stash@{1} — View a specific stash.
  • git stash apply stash@{2} — Apply a specific stash without removing it.
  • git stash pop stash@{0} — Apply and remove a specific stash.
  • git stash drop stash@{3} — Delete a specific stash entry.

Pro tip: use git stash push -m "message" to label the stash and make it easier to find later.

# Save only tracked changes with a label
git stash push -m "wip: refactor login form"

# Save including untracked files
git stash push -u -m "wip: new config files"

When should you use it?

  • When you need to switch branches but do not want to commit work-in-progress.
  • When you need a clean working directory temporarily and do not want to lose local changes.
  • When handling multiple tasks and want to keep separate stashes you can apply later.

Common pitfalls and tips

  • Conflicts can happen when applying a stash. Resolve them like a normal merge conflict and continue.
  • Use labels (-m) to avoid confusion when you have many stashes.
  • Prefer small, focused stashes. Huge stashes are harder to apply cleanly.
  • Remember: apply keeps the stash; pop removes it after applying.

Useful variations

  • Stash only specific files:
git stash push -m "wip: only app.js" -- app.js
  • Keep index (staged changes stay staged):
git stash push --keep-index -m "wip: keep staged changes"
  • Include untracked files:
git stash push -u -m "wip: include untracked"

Summary

git stash is your friend for quick context switches: save, switch, return, and restore. With a few commands you can keep your working directory clean and your flow smooth.

Stay Tuned

Want to become a Software Engineer pro?
The best articles and links related to web development are delivered once a week to your inbox.