How to keep changes when switching branches without using `git stash`

93 Views Asked by At

I made some changes on branch x but I have not staged or committed any new changes, I get:

% git checkout other/existing/branch
error: Your local changes to the following files would be overwritten by checkout:
        apps/node-be/package.json
Please commit your changes or stash them before you switch branches.
Aborting

for some reason, I was under the impression that if the changes were not staged or commited that they were would be moved over (I swear that happens sometimes), but I guess it clearly would cause conflicts, so a merge would be necessary.

Is there a flag to checkout a branch and if there are no conflicts keep the changes?

git checkout --mine other/existing/branch

the other way to do this seems to be:

git stash
git checkout other/existing/branch
git stash apply

so I guess, in a way, I would be looking for a one-line command:

git checkout --from-stash other/existing/branch

or whatever

1

There are 1 best solutions below

3
Jay On BEST ANSWER

This may run in conflicts, but you can use the --merge option (a.k.a -m) to keep your local changes, even if the files were changed between the branches you're switching from/to.

git checkout --merge other/existing/branch

or the more modern

git switch --merge other/existing/branch