Reputation: 4112
After creating a new repository using git init
and performing a first commit (into master
branch)
I then tried to edit some files, while the working directory was not clean yet, I could do git checkout -b dev
then git add .
, git commit
(into dev branch) all successfully.
But at this time after editing files in the dev branch, while the working directory is not clean yet, I cannot do git checkout master
, git asks me to stash or otherwise complete the commit before checking out to the other branches.
I'm so curious why git acts differently in this case.
Upvotes: 4
Views: 24
Reputation: 1327314
Because when the repo is just initialized, there is no branch at all.
Creating one with git checkout -b
will not change anything in the current working tree.
Similarly, If there was already the branch master
, creating a new branch means simply initializing dev
HEAD where master is, without having to modify the current working tree.
However, once a branch is created (meaning there is at least one commit), you cannot switch to another branch if that will erase some work in progress.
Getting back to master
while there are pending modification in dev
would erase said modification, which is why git stash
or git commit
is recommended.
The git checkout
man page does include:
When switching branches, if you have local modifications to one or more files that are different between the current branch and the branch to which you are switching, the command refuses to switch branches in order to preserve your modifications in context.
git checkout
will updates files in the working tree to match the version in the index or the specified tree.
In the OP's picture, the first git checkout -b dev
doesn't have to update any file from master
to match the version of said files in dev
(since dev
is just created).
But in the second git checkout master
, it would have to update file1
from dev
(currently being modified) to match the version of file1
from master
: that is why a git stash
or commit
is required before switching.
Upvotes: 2