What is Git Stash?
Git stash is a command that temporarily shelves (or "stashes") changes you've made to your working directory so you can work on something else, and then come back and re-apply the changes later. It's particularly useful when you need to:
- Switch branches without committing unfinished work.
- Pull in updates from a remote repository.
- Fix a bug or work on an urgent task before resuming your current task.
How to Use Git Stash
Stashing Your Changes
To stash your changes, navigate to your project directory in the terminal and simply run:
git stash
This command saves your local modifications and reverts the working directory to match the HEAD commit.
If you want to include untracked files in your stash, use the -u
(or --include-untracked
) option:
git stash -u
You can also provide a message to describe your stash, which can be helpful when managing multiple stashes:
git stash save "WIP: refactoring authentication module"
Viewing Stashes
To see a list of all stashed changes, use:
git stash list
This will display a list of stashes, each with an index and a description (if provided).
Applying Stashed Changes
When you're ready to reapply stashed changes, you have two main options: apply
and pop
.
Apply: Reapplies the changes from the stash but leaves the stash intact.
git stash apply
Pop: Reapplies the changes from the stash and removes the stash from the list.
git stash pop
If you have multiple stashes and want to apply or pop a specific one, you can reference it by its index:
git stash apply stash@{2}
Cleaning Up Stashes
Over time, you might accumulate several stashes that are no longer needed. To remove a specific stash, use:
git stash drop stash@{2}
To clear all stashes, use:
git stash clear
Practical Use Cases
1. Switching Branches
Imagine you're working on a feature branch and suddenly need to switch to the main branch to address a critical issue. You can stash your changes, switch branches, make the necessary fixes, and then return to your feature branch and reapply the stashed changes:
git stash
git checkout main
# Fix the issue and commit the changes
git checkout feature-branch
git stash pop
2. Pulling Updates
If you have local changes but need to pull in the latest updates from a remote repository, stashing can help avoid conflicts:
git stash
git pull
git stash pop
Conclusion
Git stash is a versatile tool that can greatly enhance your workflow by allowing you to manage uncommitted changes efficiently. By mastering git stash
, you can switch contexts quickly, handle urgent tasks without losing progress on your current work, and maintain a cleaner project history.
Start incorporating git stash
into your Git toolkit today, and you'll find your development process becomes smoother and more flexible. Happy coding!