How to Stash Git Changes
There are times when you need to switch branches to work on another project. The git stash command comes to rescue. It is used to stash the dirty state of the working directory and saves it on a stack of incomplete changes that can be re-applied later.
Steps to stashing changes
Let’s see what commands are required for stashing your changes:
Displaying the state
Firstly, you can run the git status so you can see the dirty state:
git status
Stashing Your Work
Run git stash to stash the changes:
git stash
The git stash command can also be used to create multiple stashes. Use the git stash list to view them. The code looks like this:
git stash list
Re-applying Your Changed Stashes
Run git stash pop to remove the changes from your stash and re-apply them to your working copy.
git stash pop
Run git stash apply, if you want to re-apply the changes and keep them in your stash:
git stash apply
Stashing Changed Stages
If the file you staged wasn’t restaged, you should run the git stash apply command with an --index option:
git stash apply --index
Cleaning up Stashes
Run stash drop with the name of the stash to remove it:
git stash drop
Un-applying a Stash
If you want to un-apply the most recent stash, use the following:
git stash show -p | git apply -R
Stash Meaning
The git stash command git stash shelves changes you have made to your working copy so you can do another work, and then come back and re-apply them. It takes uncommitted both staged and unstaged changes, saves them away for further use, and then returns them from your working copy.
Multiple Stashes
As mentioned above, you can also create multiple stashes. By default, stashes are identified as a "WIP" – work in progress. It comes on top of the branch and commit that you created the stash from.
Staged and Unstaged Changes
Running git stash will stash both git changes not staged for commit and the ones staged for it. But git stash will not stash new files that have not yet been staged and the ones that have been ignored. In those cases, the -u option (or --include-untracked) helps also stash the untracked files.
git stash -u
You can add changes to ignored files as well by using the -a option (or --all) when running git stash.
git stash -a
How to Apply Patch
Git does not support a stash unapply command, but it is possible to unapply the stash by retrieving the patch associated with a stash and applying it in reverse:
git stash show -p stash@{0} | git apply -R
Git assumes the most recent stash if you don’t specify a stash:
git stash show -p | git apply -R
But there also exists git undo extension that makes it easier and more convenient undoing commits, applying stashes and pushed merges.