5

I have some uncommitted changes in my current branch.

I have to rebase from another dev branch but I want to stash my changes first.

If I do a git stash then I git rebased the dev branch, will I lose the stash?

lost9123193
  • 10,460
  • 26
  • 73
  • 113

2 Answers2

7

If I do a git stash then I git rebased the dev branch, will I lose the stash?

No.

Remember, a stash is just a commit1 that's on no branch. Like any commit, it sticks around until it has no name any more. That means that as long as it's find-able by the name stash, it's still in your repository.2

You will eventually need to git stash apply the saved stash, and then if everything seems to have worked, git stash drop the saved stash to remove access to the commit from the name stash. The commit actually goes away on its own some time later, but in effect, git stash drop deletes it.

Note that git stash pop is just git stash apply && git stash drop: i.e., apply the stash, then if Git thinks the application worked, drop the stash. If you applied the stash somewhere other than where you wanted to—this happens a lot—and Git sees success here, you've now lost your stash. So it's best to get in the habit of separate apply-then-drop, just in case.

Side note: Since Git version 2.6, git rebase can automatically stash before rebasing. I don't like this mode myself, but if you do, see Why won't --autostash option work ??? (used with git pull --rebase) and VonC's answer to a related question, which notes a bug not fixed until Git 2.14.


1Actually it's at least two commits, and sometimes three; but until you start doing advanced things with stashes, they act like just one commit.

2This means you should not name a branch stash. Git will be just fine if you do, but you'll probably get confused. :-)

torek
  • 448,244
  • 59
  • 642
  • 775
  • You don't necessarily “lose” a stash when it's dropped. The ref is dropped from the stash log, but the process of dropping outputs the ref hash to your terminal, which you can use to “recover” the diff with `git reset [hash]`. – coreyward Jun 06 '18 at 00:51
  • @coreyward: sure, if you're quick enough. But it's no longer in any reference or reflog, so if an auto gc runs and the stash is at least `pruneExpire` days old (default 14), it will get gc-ed. (I'd point a new branch or tag name at it, rather than using `git reset`—the `stash` code will take such names.) – torek Jun 06 '18 at 01:38
2

No, you will not lose the stash. Git will rarely remove refs unless you're explicit about it and then do a gc.

You can safely stash changes, rebase or checkout another branch, and then apply or pop your stashed changes. If you do a git stash pop and the changes conflict, git will apply your changes (and show merge conflicts) but will not automatically pop the stash off of your stashed commits.

coreyward
  • 77,547
  • 20
  • 137
  • 166