In this lesson, you will learn how to pause your current work using the git stash command, allowing you to switch branches without being forced to make an incomplete or "messy" commit.
The Problem: Interruptions
Imagine you are halfway through a new feature on a branch called feature-x. Suddenly, your manager asks you to fix a critical bug on the main branch immediately. You cannot commit your current work because it isn't finished, but Git prevents you from checking out a different branch because your uncommitted changes would be overwritten.
The Solution: The Stash
Git provides a "stash" area—a temporary storage space where you can tuck away your modified files. Think of it like a clipboard for your entire working directory.
When you run git stash, Git takes your unstaged and staged changes, saves them in a hidden storage area, and resets your working directory to match the last commit. Your project is now clean, and you are free to switch branches.
Here is how you use it:
-
Stash your work:
git stashYour working directory is now clean, and your changes are saved safely in the stash.
-
Switch branches and work: You can now
git checkout main, fix that critical bug, commit your changes, and return to your feature branch. -
Retrieve your work: Once you are back on your original branch, bring your saved work back:
git stash popThis command applies the changes you saved earlier back onto your working directory and removes them from the stash list.
A Quick Note
If you have multiple stashes, you can view them using git stash list. It is best practice to use pop only when you are sure you want to re-apply the changes and remove them from storage. If you want to apply the changes but keep a copy in your stash list just in case, you can use git stash apply instead.
Key Takeaway: The git stash command allows you to save uncommitted work to a temporary storage area, keeping your working directory clean so you can switch branches and address urgent tasks without losing your progress.