Shelving Changes Temporarily with git stash (save, pop, apply, drop)
Shelving Changes Temporarily with git stash (save, pop, apply, drop)
Software development is full of interruptions: you are deep in the middle of writing an unfinished feature when an urgent production bug alert arrives. Your current code is broken and half-written—you can't commit it, but you also can't lose it. The git stash command is your temporary clipboard.
1. How Git Stash Works
git stash takes the dirty state of your working directory (all modified tracked files and staged changes) and saves it onto an internal stack of unfinished changes, returning your working directory to a clean HEAD state!
2. Core Stash Commands
A. Stashing Your Changes
B. Including Untracked Files (-u)
By default, git stash only stashes tracked files. If you created brand new files that haven't been committed before, add the -u (or --include-untracked) flag:
3. Inspecting and Restoring Stashes
A. View All Saved Stashes (git stash list)
Output:
B. Restoring Changes: git stash pop vs. git stash apply
| Command | Restores Changes to Working Tree? | Removes Stash from Stack? |
|---|---|---|
git stash pop | Yes | Yes (deletes the stash item if no conflicts occur) |
git stash apply | Yes | No (leaves the stash on the stack so you can reuse it elsewhere) |
4. Cleaning Up Stashes
Stashes accumulate over time and consume disk space. Clean them up regularly:
5. Typical Real-World Scenario
- 1Working on
feature-redesign, edited 3 files. Code doesn't compile yet. - 2Manager asks for urgent hotfix on
main. - 3You stash:
git stash push -m "WIP redesign". - 4Switch to main:
git switch main. - 5Fix bug, commit, and push:
git commit -am "fix: hotfix security header"->git push. - 6Switch back:
git switch feature-redesign. - 7Restore your work:
git stash pop. - 8Continue coding right where you left off!
Practice Quiz
git stash do?git stash ignore newly created untracked files by default?git stash pop and git stash apply?Undoing Changes Safely: git restore, git reset, and git revert
Continue learning with hands-on practice, examples, and exercises in the upcoming topic.
Related Lessons
Practice Quiz
Test your understanding of this lesson with 5 questions. Each question has one correct answer.