0

I was watching this video and exactly at time 24:50 it says:

You can't switch branches in git unless your working directory is clean

I have tested this in a test repository, modifying a file and switching branch, and I could do it! The guy works in GitHub so I doubt he doesn't know what he is talking about. Did Git changed its behaviour lately?

Update

This is my log: http://pastebin.com/dFTwHrET

2 Answers 2

6

It's more defensive that that.

If you have uncommitted changes that would be overwritten by switching branches, Git will not allow you to do so. If the changes are not impacted by switching branches, then nothing is stopping you.

Say you have a simple git repository with a single file.

Checkout a new branch and make changes to the contents of this file. Without committing the changes, try to switch back to the original branch. You will be able to do this as the head commit is the same.

Checkout a new branch and make changes to the contents of this file. Commit this change. make another change, but without committing the changes, try to switch back to the original branch. You won't be able to do this.

Since you can't switch branches, discard your changes (git reset --hard head) and then add another file. Without committing this addition, try to switch branches, you will be able to do this.

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

8 Comments

But that doesn't cause a conflict. Rather than make a single change in your second branch, commit the change then make another change, and without checking it in, try to switch branches.
If you think about it, just switching branches and making an uncommitted change doesn't change anything because the head commit of both branches is the same. One you commit a change, then this is not the case anymore.
I see. So the speaker's statement applies, as long as there is AT LEAST 1 commit with the branch pointer. Correct?
(I've updated my answer again). And that is sort of correct. If there is a commit, and you have unstated changes that will be over-written by a change in branch.
@TimCastelijns Don't worry about it, I've been using git for literally years and I still learn new things about it.
|
0

Agree with @Abizem's answer.

In case you want to checkout to a new branch without committing the current changes on the branch. Then you can use stashing, stash the changes on the current branch with any identifier and then checkout to the new branch. Git Tools Stashing

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.