Learning Objectives
- Understand what Git stash is and when to use it
- Learn basic and advanced stashing operations
- Master stash management and organization
- Discover best practices for working with stashes
Understanding Git Stash
Git stash is a powerful feature that temporarily stores modified tracked files, allowing you to switch contexts without committing incomplete work. It's like a clipboard for your changes.
Quick Save
Save work in progress without creating a commit, perfect for switching tasks quickly.
Clean Workspace
Keep your working directory clean while preserving incomplete changes.
Context Switch
Easily switch between different tasks or branches without losing work.
Basic Stashing Operations
Let's look at the essential stashing commands you'll use most frequently:
Creating Stashes
# Basic stash$ git stash # Stash with a message$ git stash save "Work in progress on login feature" # Stash including untracked files$ git stash -u # Stash including ignored files$ git stash -a
Applying Stashes
# Apply most recent stash$ git stash apply # Apply specific stash$ git stash apply stash@{2} # Apply and remove stash$ git stash pop # Apply with index$ git stash apply --index
Advanced Stashing Techniques
Git stash offers advanced features for more complex scenarios:
Partial Stashing
# Stash specific files$ git stash push -m "Update config" config.json # Interactive stashing$ git stash -p # Stash single file$ git stash -- path/to/file.txt
Stash Branch Operations
# Create branch from stash$ git stash branch new-branch # Apply stash to branch$ git checkout feature-branch$ git stash apply
Managing Stashes
Proper stash management is crucial for maintaining organized work:
Viewing Stashes
# List all stashes$ git stash list # Show stash contents$ git stash show # Show detailed stash diff$ git stash show -p # Show specific stash$ git stash show stash@{1}
Cleaning Up Stashes
# Remove single stash$ git stash drop stash@{0} # Remove all stashes$ git stash clear # Remove applied stash$ git stash pop
Common Stashing Scenarios
Here are some typical situations where stashing is particularly useful:
Quick Branch Switch
# Save current work$ git stash save "WIP: Feature implementation" # Switch branches$ git checkout hotfix-branch # Work on hotfix... # Return to feature$ git checkout feature-branch$ git stash pop
Pull with Local Changes
# Stash changes$ git stash # Pull updates$ git pull origin main # Reapply changes$ git stash pop
Stashing Best Practices
- Use descriptive messages:
Always include meaningful messages with your stashes
- Clean up regularly:
Don't let stashes accumulate; remove them when no longer needed
- Verify before popping:
Check stash contents before applying to avoid conflicts
What's Next?
Now that you understand stashing, in the next lesson you'll learn about:
- Advanced branch operations like cherry-picking
- Interactive rebasing and commit squashing
- Managing complex branch operations