Basic Git Series: Using Git Stash

Adam Sturge | Sep 26, 2023 min read

Overview

Git stash allows you to temporarily save changes you’ve made to your working directory without committing them. This is useful when you need to switch contexts or branches but aren’t ready to commit your current work.

Steps

  1. Stash your current changes:
git stash
  1. Stash with a descriptive message:
git stash save "Work in progress for feature x"
  1. List all stashes:
git stash list
  1. Apply the most recent stash (keeps the stash):
git stash apply
  1. Apply a specific stash:
git stash apply stash@{2}
  1. Apply and remove the most recent stash:
git stash pop
  1. Remove a stash without applying it:
git stash drop stash@{1}
  1. Clear all stashes:
git stash clear

Common Issues

  • Untracked files not stashed: By default, git stash only stores tracked files. Use git stash -u to include untracked files
  • Merge conflicts when applying stash: Resolve them like normal merge conflicts
  • Accidental stash drop: Once dropped, stashes can be difficult to recover; use git fsck --unreachable to find dangling commits

Additional Notes

  • Create a branch from a stash:
    git stash branch new-branch-name stash@{1}
    
  • View the contents of a stash:
    git stash show -p stash@{0}
    
  • Stashing is local to your machine and not pushed to remote repositories
  • Consider using a dedicated feature branch instead of stashing for longer-term work