4

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.

Edit (adding screenshot)

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

4 Comments

Although I use git branch and git shows that there is master branch, in fact there are no branches until the first commit, right?
@Kongthap, yes, git branches are just the files containing sha1 or other references to the existing commits.
@VonC, I believe in what you said, that's why I'm curious according to what I have tried, this is nothing actually just for learning to understand git more
@Kongthap I have edited my answer to address and illustrate your picture.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.