Git Stashing and Shelving
Introduction
In this lesson, we will explore two important techniques in Git: Stashing and Shelving. These features allow developers to temporarily save changes that are not yet ready to be committed. This is particularly useful when you need to switch branches or work on a different task without losing your current progress.
Git Stashing
What is Git Stashing?
Git Stashing allows you to save your uncommitted changes in a stack-like structure. It effectively lets you "stash" your work and revert to a clean working directory.
Basic Commands
-
Stash Changes:
git stash
This command will stash all your changes.
-
List Stashes:
git stash list
View all stashed changes.
-
Apply Stash:
git stash apply
Reapply the most recent stash.
-
Drop Stash:
git stash drop stash@{0}
Remove a specific stash.
-
Clear All Stashes:
git stash clear
Remove all stashed changes.
Example Scenario
Imagine you're working on a new feature and need to switch to the master branch to address a bug:
git stash
git checkout master
git pull
git checkout feature-branch
git stash apply
Git Shelving
What is Git Shelving?
Git Shelving is often considered a more advanced feature available in some Git GUIs. It allows you to store changes in a more organized way than stashing, often with more contextual information.
Common Commands
-
Shelve Changes:
git shelve
Store your changes in the shelf.
-
List Shelves:
git shelf list
View all shelved changes.
-
Unshelve Changes:
git unshelve
Reapply the most recent shelved changes.
-
Drop Shelf:
git shelf drop
Remove a specific shelf.
Best Practices
- Always provide a descriptive message when stashing or shelving changes.
- Use stashing for quick, temporary changes that you’ll return to soon.
- Consider shelving for more complex changes that require context.
- Regularly clean up your stash or shelf to avoid clutter.
FAQ
What happens to stashed changes if I switch branches?
Your stashed changes remain intact and can be reapplied on any branch.
Can I stash untracked files?
Yes, you can stash untracked files by using git stash -u
.
What is the difference between stash and shelf?
Stash is for quick temporary storage, while shelf is more organized and contextual for larger changes.