Temporary Save (git stash)
Imagine the following fairly common office scenario:
- You are halfway working on the
feature-loginbranch. You have modified files but your code is completely unusable (it doesn't compile, nor build). - Suddenly, your boss notifies you that there is a very serious error in the main branch (
main) that you must solve Immediately! - You try to
git switch mainto go fix it.
Git will stop you with an error. It will tell you that you have unsaved changes that would be overwritten if you switch branches.
You don't want to make a commit because the login code is half-finished garbage, but you also don't want to do a restore and lose your hour of progress. What is the solution?
Enter git stash to the rescue
The "stash" (hide) command takes all your current dirty changes and puts them temporarily in a drawer (an invisible Git clipboard), returning your working directory to a clean and neat state.
git stash
Upon doing so:
- Your changes disappear from your files.
- Your working directory returns to the state of your last clean official commit.
- You can now make the jump to
mainfreely and solve emergencies.
Recovering what is hidden
Once you solved your boss's problem and pushed it to GitHub, you return to your working branch git switch feature-login.
You want to resume your previous work. You open the drawer and return it to your files:
git stash pop
Your half-written files magically reappear and you can continue as if nothing had happened.
Useful Tip: You can run
git stash listat any time if you want to see how many things you have hidden in your temporary drawers in case you had forgotten.