-1

git checkout by default leaves alone the uncommitted changes in the working tree directory. Then is it necessary to run git stash push before git checkout (and then run git stash pop at some later point after git checkout)? Or when is it necessary, and when is it not?

My question comes from https://stackoverflow.com/a/48156644/156458 and is more general.

halfer
  • 19,824
  • 17
  • 99
  • 186
Tim
  • 1
  • 141
  • 372
  • 590
  • 2
    `when is it necessary?`, don't bother, git will tell you if you need to stash. If there is a conflict, you need to stash your changes, otherwise not necessary. – balki Jan 22 '19 at 23:30

1 Answers1

1

If there are uncommitted changes that will be overwritten by git checkout the command will complain and abort. In that case git commit or git stash is necessary.

If there are uncommitted changes that will not be overwritten by git checkout the command succeeds and the changes spilled into the new branch. If you don't want to see these changes in the new branch use git commit or git stash before git checkout.

Unlike other commands (like git pull and git rebase) git checkout doesn't have option --autostash because it's meaningless: in most cases you don't want to automatically do git stash pop when switching to a new branch.

phd
  • 82,685
  • 13
  • 120
  • 165
  • Thanks. Does `git checkout -m` act like a sequence of `git stash push`, `git checkout` and `git stash pop`? – Tim Jan 23 '19 at 05:05
  • `git checkout -m` does merge; it's similar to `git stash pop` but I doubt it's the same. – phd Jan 23 '19 at 05:12
  • Why " in most cases you don't want to automatically do git stash pop when switching to a new branch"? – Tim Jan 23 '19 at 23:17
  • Because in most cases the stashed code belongs to the branched that is being put in the background, not to the branch being checked out to the work tree. In a rare case when the user wants to merge the changes into the new branch she calls `git stash apply` (or `pop`) manually. – phd Jan 24 '19 at 01:32