- Published on
Git Stash: Temporarily Save Your Changes
- Authors
- Name
- Hieu Cao
Introduction
Git stash is a handy feature that allows developers to save uncommitted changes temporarily. This is particularly useful when you need to switch branches or work on a high-priority task without losing your current progress.
In this blog, we will cover the basics of Git stash, including common commands and practical use cases to help you integrate it into your workflow.
What Is Git Stash?
Git stash acts like a "clipboard" for your code, where you can store changes that haven't been committed yet. These changes can include modified files, staged files, or new files. Once stashed, your working directory reverts to a clean state, making it easy to switch contexts.
Why Use Git Stash?
Some common scenarios where Git stash is helpful include:
- Switching branches: Temporarily save your progress to check out another branch.
- Code experimentation: Test changes without committing them.
- Interruptions: Pause your current work to handle an urgent bug fix or task.
Basic Git Stash Commands
1. Stash Changes
To stash your changes, use the following command:
git stash
This saves all modified and staged files to the stash.
2. List Stashed Changes
View all stashes saved in your repository:
git stash list
Example output:
stash@{0}: WIP on main: Add feature implementation
stash@{1}: WIP on main: Fix typo in README
3. Apply Stashed Changes
To apply the most recent stash without removing it from the stash list:
git stash apply
If you want to apply and remove the stash, use:
git stash pop
4. Drop a Stash
To delete a specific stash:
git stash drop stash@{0}
To clear all stashes:
git stash clear
Example Workflow
Scenario:
You are working on a feature but need to switch branches to fix a critical bug. Here's how Git stash can help:
Save your changes:
git stash
Switch to the bugfix branch:
git checkout bugfix
Fix the bug and commit your changes:
git commit -m "Fix critical bug"
Return to your feature branch:
git checkout feature-branch
Apply your stashed changes:
git stash pop
Conclusion
Git stash is a simple yet powerful feature that can help you manage your workflow more efficiently. By mastering its basic commands, you can handle interruptions, switch tasks seamlessly, and keep your changes safe.
Try incorporating Git stash into your daily development routine, and experience the benefits of a more flexible workflow.
Happy coding!