Enrique Moreno Tent
Enrique Moreno Tent

Reputation: 25297

Switching branches in GIT with Working directory not clean

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

Upvotes: 0

Views: 1414

Answers (2)

Bijendra
Bijendra

Reputation: 10053

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

Upvotes: 0

Abizern
Abizern

Reputation: 150675

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.

Upvotes: 6

Related Questions