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
cd testgitstash # change to that directory
git init # init git repo
echo test1 > file1.txt # create 2 files
echo test2 > file2.txt
git add . # add both files
git commit -m "Initial commit" # commit both files
git checkout -b new-branch # create a new branch and switch to that branch

On top of that you have some pending changes on new-branch

echo change > file1.txt # change file1
git commit -am "update" # commit change
echo change2 > file1.txt # change file1 again

The problem

If you want to switch back to master, you will get an error message:

$ git checkout master
error: Your local changes to the following files would be overwritten by checkout:
Please, commit your changes or stash them before you can switch branches.


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.


- 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 :)