Introduction
In team development, you often need to switch branches to address an urgent bug fix while in the middle of writing code for a feature branch.
While you can commit your half-finished work as a temporary “WIP” commit, a cleaner approach is to use git stash.
This article covers advanced git stash techniques, including saving untracked files, labeling stash items, and restoring specific files from a stash.
1. The Basics of git stash
Let’s review the most common commands:
# Save current changes (both staged and unstaged) to the stash stack
git stash
# List all saved stash entries
git stash list
# Restore the most recent stash entry (stash@{0}) and remove it from the stack
git stash pop
# Restore a stash entry without removing it from the stack
git stash apply
2. Advanced Stash Techniques
① Including Untracked Files (New Files)
By default, git stash only saves changes to files already tracked by Git. Newly created, untracked files are left behind in your working directory.
To stash both tracked and untracked files, add the -u (--include-untracked) flag:
# Save all changes, including newly created files
git stash -u
② Naming Stash Entries
As you save multiple stash entries, the list can become difficult to navigate. You can add a descriptive message to identify each entry:
# Save a stash with a descriptive message
git stash push -m "WIP: login form styling"
③ Dropping and Clearing the Stash Stack
Delete specific entries or clear the entire stack to keep it organized:
# Delete a specific stash entry (e.g., the second entry)
git stash drop stash@{1}
# Delete all entries from the stash stack (Note: this cannot be undone)
git stash clear
3. Restoring Specific Files from a Stash Entry
If you only want to restore a single file (e.g., config.json) from a stash entry rather than all changes, you can check it out individually:
# Check out a specific file from the target stash entry
git checkout stash@{0} -- path/to/file.js
This returns the specified file to your working directory while keeping the remaining changes in the stash.
Conclusion
The git stash command is an effective way to manage your working directory during branch context-switches.
- Use
git stash -uto ensure newly created files are saved. - Add descriptions using the
-mflag to identify entries later. - Restore files selectively using
git checkout stash@{X} -- <path>.
Using these techniques helps prevent code loss and keeps your branch history clean.
