Git stash simply saves your staged and unstaged changes (uncommitted though) for a later use, so you could checkout another working directory, or even continue your work in the same working directory as clean as possible. There are few handy stash operation I want to explore as you might need them in the future.
Prerequisites
- Git
Solution
Stashing current changes:
git stash
Note(s): You can do the same with git stash push
as they are the same command.
List all Git stashes:
git stash list
To show a certain Git stash diff between the HEAD commit and the stash, run:
git stash show stash@<index>
Give a certain Git stash a name:
git stash push -m "devcoops_1"
To stash a single file, run:
git stash push -m "devcoops_2" index.html
Stash changes to a branch, run:
git stash branch <branch>
Note(s): This has to be a non-existing branch, as it will create and checkout the branch.
git stash apply and pop
git stash apply
will apply all changes from the stash to the current working directory of the checked out branch. For instance:
git stash apply index@{2}
git stash pop
basically will do the same as git stash apply
except the last part. It will delete the stash tho once the stored changes are applied. git stash pop
= git stash apply
&& git stash drop
. Example:
git stash pop index@{3}
Note(s): If you don’t specify the stash index, it will apply or pop (whatever the case might be) the latest one.
unstaged files only == exclude staged
To exclude the staged files, run:
git stash push --keep-index
untracked and ignored files
For untracked files, run:
git stash --include-untracked
or the short version: -u
.
Regarding ignored files, execute the following command:
git stash --all
or just -a
.
removing stashes
Delete a single stash:
git stash drop stash@{<index>}
Delete all stashes:
git stash clear
Conclusion
To find more neat Git commands and hacks, simply browse the Git category. Feel free to leave a comment below and if you find this tutorial useful, follow our official channel on Telegram.