Common everyday scenario: you are working on your feature branch fixing a bug and your boss asks you for a build. You need to switch back to your main dev branch. Before that happens, you have to take care of all your current changes. You can either commit if you are ready for it, or maybe you have only modified a few lines and can simply revert your changes.
Well there is a better solution: git stash.
Setting up the stage
We have 2 files: file1.txt
and file2.txt
and 2 branches, master
and new-branch
.
If you want to follow along here is the script
mkdir testgitstash # create directory |
On top of that you have some pending changes on new-branch
echo change > file1.txt # change file1 |
The problem
If you want to switch back to master
, you will get an error message:
$ git checkout master |
Git does not allow you to switch back to master
because you have changes on new-branch
.
One solution: git stash
Stash the changes
Instead of committing your changes or reverting, you can stash them with:
$ git stash save "changes on new-branch" |
Switch branch
You can now switch back to master
$ git checkout master |
Do whatever changes you want on master, and when ready, go back to new-branch
.
$ git checkout new-branch |
Unstash the changes
$ git stash pop |
Your changes will be put back and you can continue what you were doing initially.
Notes
- Your changes are stashed on a stack
You can stack several changes and check the current stash stack using:
$ git stash list |
You can also unstash a specific stash by using
$ git stash pop "stash@{1}" |
- Git stash pop can be split in two
Git stash pop is the combination of two other commands:
$ git stash apply |
which applies the last stash and:
git stash drop |
which destroys the last stash
Hope this helped, there would be much more to say on this suject but I hope this will give you a place to start :)