Git’s stash
and pop
commands provide a convenient way to temporarily store uncommitted changes and reapply them later. This allows for easy context switching without losing work or creating unnecessary commits.
Consider this common scenario in a data science project:
# Working on improving a linear regression model
git checkout -b improved-model
# Editing model.py with new improvements
# Urgent: Critical bug discovered in data loading function
git stash save "WIP: Improving linear regression model"
# Switch to main branch to fix the bug
git checkout main
# Fix the bug in data_loader.py
git add data_loader.py
git commit -m "Fix critical bug in data loading"
# Return to model improvement
git checkout improved-model
git stash pop
# Continue enhancing the model
git add model.py
git commit -m "Complete improved model with scaling"
In this workflow:
git stash save
temporarily stores your uncommitted model improvements with a descriptive message.- You switch to the main branch with a clean working directory to address the critical bug.
- After fixing the bug,
git checkout improved-model
returns you to your feature branch. git stash pop
retrieves your saved changes, allowing you to resume work on the model.
This approach helps maintain a clean, organized development process while providing the flexibility to address urgent issues without losing progress on ongoing tasks.