Is git stash branch-specific or for the whole repository?


I went into a branch and did some work. I wanted to go into another branch but didn’t want to commit so I did git stash. Then I did git checkout <otherbranch>. I did some work there and, just like in the first branch, I wanted to switch out of it before committing the work. So I did git stash there too. I switched back to the first branch and tried to unstash it (git stash pop) thinking it would get the stash from that specific branch. I was surprised that it unstashed the stash from <otherbranch> (latest stashed). I was under the impression that stash is branch-specific but this behavior indicates that there is only one stash for the whole local repository.

Is git stash branch-specific or for the whole repository? If it is for the whole repository, can I pass options to it to make it branch-specific?


To see the current stash stack:

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

Leave a Reply