Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

git checkout with changes from one branch to another [duplicate]

Tags:

git

I am on branchX. I make some changes in my working directory. They all get reflected in "Changes not staged for commit". Now I do git checkout branchY. Sometimes I get the changes getting moved into "Changes not staged for commit" of the branchY like :

M <some file1 path>
M <some file2 path>

and sometimes git gives me this message - Please commit your changes or stash them before you switch branches.

How does git decide it when to reflect the changes and when to abort ? Should not git never move "Changes not staged for commit" changes of one branch into other if I checkout without committing them ?

like image 823
Number945 Avatar asked Nov 01 '25 13:11

Number945


1 Answers

The second message you're quoting (Please commit your changes or stash them before you switch branches.) occurs when moving your pending changes would create conflicts on the to-be-checked-out branch.

When no conflicts are detected, the working tree is first updated regarding the commit HEAD is now pointing to, then your pending changes are replayed above and you're ready to add more changes or commit right away.

And as a sidenote, it's widely considered a good practice to always return to a clean state before checking another branch out. Committing on the branch* or stashing changes are probably the most common ways to achieve this.

(* since this commit is only local for now, you'll have the opportunity to amend it or drop it entirely when you'll return to this branch.)

like image 200
Romain Valeri Avatar answered Nov 04 '25 06:11

Romain Valeri