Is git stash branch-specific or for the whole repository?
To see the current stash stack:
git stash list
To pick a specific stash from the stack, refer to it by the stash@{number}
shown by the above.
If you want the behavior to be per-branch, you can just make a commit (or multiple commits) on the branch. You can always "unmake" the commit(s) later (e.g., with git reset
, either --soft
or --mixed
; see the git reset documentation; or with git rebase -i
to keep only the eventual "real" commit(s) while discarding the temporaries).
(To really emulate git stash
you need at least two commits, one for the index state and one for the work-tree state. If you're not planning to save and restore the index state, though, you can just git add -A
the entire work-tree state and put that in the temporary commit. Alternatively, git stash
is a shell script so you could copy and modify it pretty easily to make it work per-branch by default, using, e.g., refs/pb-stash/branch
as its working name-space, rather than the single global refs/stash
for the entire repo. You'd still be able to bring a stash from one branch to another by naming it explicitly.)
git stash
is not per-branch.
- Instead of
git stash
(which can be lost easily when you have lots of stashes and branches) - I suggest doing a
git commit
to save the unfinished code in your branch and when you are ready to finish the code do agit reset ${COMMIT_HASH_VALUE}
to get the unfinished code back git commit
andgit reset
when used together correctly can simulate agit stash
for a specific branch
Here is a common real-life scenario that demonstrates the value and the usage the commit
and reset
commands:
- you are working on feature branch X and your code doesn't even compile or pass the tests
- there is a bug that is higher priority than the current new feature and so you must start work immediately on the bug fix
- rather than do a git stash (and the stash gets lost in the mix because you have many stashes and many branches)
- you can do a
git commit
on feature branch X- write down the
COMMIT_HASH_VALUE
for later
- write down the
- checkout a new branch Y for the hot fix
- finish the hot fix on branch Y (do a merge request to get the hot fix into the baseline and delete the hot fix branch)
- then checkout the feature branch X again
- to pop your unfinished work that didn't compile or pass testing --> just do a
git reset ${COMMIT_HASH_VALUE}
(FYI the default for git reset
is --mixed
)