Introduction
Git stash is a powerful command that allows you to temporarily save your uncommitted changes, allowing you to switch branches or work on another task without losing your progress.
Basic Usage
- Stashing changes:
git stash
This saves your current working directory and index state into a stash.
- Listing stashes:
git stash list
Shows a list of all stashed changes.
- Applying a stashed change:
Without removing from stash:
git stash apply
Removing from stash:
git stash pop
- Dropping a stashed change:
git stash drop stash@{0}
Replace stash@{0}
with the specific stash you want to delete.
- Clearing all stashes:
git stash clear
Example Workflow
Let's say you're working on a feature branch and you're halfway through when you need to fix a bug on the main branch:
- Stash your changes:
git stash
- Switch to the main branch:
git checkout main
- Fix the bug:
# Make necessary changes
git add .
git commit -m "Fixed bug"
- Switch back to your feature branch:
git checkout feature_branch
- Apply your stashed changes:
git stash pop
Additional Tips
- Include untracked files
git stash
does not include untracked files.
For including untracked files:
git stash save --include-untracked
- Stash with a message:
git stash save "My stash message"
- Create a branch from a stash:
git stash branch new_branch stash@{0}
- Inspecting a stash:
git stash show stash@{0}
Question and Answer
Is this possible to stash and work on the same branch?
Yes, you can stash and work on the same branch. This is actually a common use case for git stash.
# Stash your current changes
git stash
# Work on a different task
# ... make changes ...
# Apply the stashed changes
git stash pop
Conclusion
This feature of git come handy many times. But, I know you forget things just like me. So, just revisit this post when you need to stash someday. Thank you.
git version control tool